System.Drawing.Common workaround in .NET6
System.Drawing.Common workaround in .NET6
Intro
最近有不少小伙伴在升級 .NET 6 時遇到了 System.Drawing.Common 的問題,同時很多庫的依賴還都是 System.Drawing.Common?,而 .NET 6 默認(rèn)情況下只在 Windows?上支持使用,Linux 上默認(rèn)不支持這就導(dǎo)致在 Linux 環(huán)境上使用會有問題,所以想介紹下?.NET 6 中?Linux 上使用 System.Drawing.Common 的解決辦法
App Context
在項(xiàng)目啟動時,配置 AppContext Switch,設(shè)置 System.Drawing.EnableUnixSupport,示例代碼如下:
System.AppContext.SetSwitch("System.Drawing.EnableUnixSupport",?true);Runtime Config Json
在應(yīng)用 build/publish 之后,會有一個 *.runtimeconfig.json我們可以直接修改這個文件,在這個配置文件中添加一個 configProperties 節(jié)點(diǎn)(如果不存在的話),并在該節(jié)點(diǎn)下增加 System.Drawing.EnableUnixSupport 配置,配置如下:
{"runtimeOptions":?{"configProperties":?{"System.Drawing.EnableUnixSupport":?true}} }MS Build
我們也可以在項(xiàng)目文件中添加一個下面的配置,作用和上面的直接修改 runtimeconfig.json 效果一樣,只是 .NET SDK 會在生成的時候?qū)⑦@個配置寫入到 runtimeconfig.json 中
<ItemGroup><RuntimeHostConfigurationOption?Include="System.Drawing.EnableUnixSupport"?Value="true"?/> </ItemGroup>Environment Variable
除此之外我們也可以配置環(huán)境變量 DOTNET_System_Drawing_EnableUnixSupport 來啟用 Unix 支持
Dockerfile 示例:
ENV?DOTNET_System_Drawing_EnableUnixSupport=trueUnix 示例:
export?DOTNET_System_Drawing_EnableUnixSupport?trueMore
個人推薦使用項(xiàng)目文件配置或者是環(huán)境變量的方式,如果不想修改代碼,就使用環(huán)境變量的方式,如果覺得環(huán)境變量不方便就使用項(xiàng)目文件配置,直接修改 runtimeconfig.json 的方式有點(diǎn)不太好維護(hù),至于 AppContext Switch 個人感覺有點(diǎn)侵入代碼,不如項(xiàng)目文件或者環(huán)境變量干凈
如果基于 Docker 容器部署,更加推薦使用環(huán)境變量方式,直接在 Runtime 鏡像中配置一個環(huán)境變量即可,這樣無論什么地方需要部署都已經(jīng)寫在了鏡像環(huán)境中,在哪里跑都是一樣的,可以參考:https://github.com/OpenReservation/ReservationServer/blob/dev/Dockerfile#L10
References
https://docs.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/system-drawing-common-windows-only
https://github.com/dotnet/designs/pull/234
https://github.com/dotnet/runtime/pull/55962
https://docs.microsoft.com/en-us/dotnet/core/run-time-config
https://guochen2.github.io/2021/11/13/netcore/net6%E7%BB%98%E5%9B%BE%E7%BB%84%E4%BB%B6System.Drawing.Common%E5%BC%82%E5%B8%B8/
https://github.com/dotnet/sdk/blob/a5f5bb5183517cb301050288b25c9c727e52e8a6/src/Tasks/Microsoft.NET.Build.Tasks/GenerateRuntimeConfigurationFiles.cs#L166
https://github.com/OpenReservation/ReservationServer/blob/dev/Dockerfile#L10
總結(jié)
以上是生活随笔為你收集整理的System.Drawing.Common workaround in .NET6的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 当 dotnet-monitor 遇上
- 下一篇: .NET6之MiniAPI(一):开始M