.NET Core 离线开发与编译-初步
这是.NET Core离线开发与编译系列的第一篇。本系列目录如下:
很多时候为了保密需要,在甲方现场,我们是没有连接外网的权限的。这对于我们在现场发布新版程序很不友好。一个行之有效的办法就是通过paket
管理依赖。
在线开发与本地缓存
和传统的.Net Framework不同,.Net Framework
开发会创建一个packages/
文件夹,把直接依赖和间接依赖都全部塞进去,但是这种方式在.NET Core
里已经被抛弃了。现代的.NET Core
项目都会共享依赖于一个全局位置的文件夹,以避免重复下载依赖。
比如,当你创建一个新项目:
dotnet new console -lang C#
dotnet add package Newtonsoft.Json
dotnet restore
更新Program.cs
:
using Newtonsoft.Json;
var x = new { A = "a", B = 0};
var str = JsonConvert.SerializeObject(x);
Console.WriteLine(str);
直接运行项目就可以得到结果:
> dotnet run
{"A":"a","B":0}
问题是,你能发现project-assets-json.png与项目有相关依赖被缓存到了哪了吗?
Offline
一旦在离线环境下,仅有源码、而无依赖,你的代码如何编译?让我们试试模拟断网环境。
清除缓存
dotnet nuget locals all -c
- 断网
- Oooooooooooooooops...
也许你会说,可以直接把*.nuget
包下载就行。OK,思路是对的。至少对于不包含间接依赖的依赖,你的确可以这样搞;但是对于含有间接依赖的依赖,而那些间接依赖可能又会依赖其它依赖,你又如何处理?
Paket 拯救你
在我看来,Paket
的最大优势是,让我们可以最大确定性地管理依赖:
- 可以锁死直接依赖和间接依赖
- 可以缓存依赖。如果你还记得
npm
里left-pad
事件,就应该明白缓存本地依赖的重要性。尽管nuget
比npm
好了很多,但是微软是有权利删除一些库的,更何况一些第三方的nuget仓库? - 可以引用一个
github
仓库 - 甚至可以引用一个网页上的源码
Paket的简单使用
创建一个项目
mkdir CSharpConsoleWithPaket
cd ./CSharpConsoleWithPaket
dotnet new console -n CSharpConsole -lang C#
dotnet new sln
dotnet sln add dotnet sln add ./CSharpConsole
安装 paket:
dotnet tool install paket --tool-path .paket
使用paket管理依赖:
./.paket/paket.exe init
./.paket/paket.exe add Newtonsoft.Json --project ./CSharpConsole/CSharpConsole.csproj
确认paket.dependencies
: e.g. the target framework
source https://api.nuget.org/v3/index.json
storage: none
framework: net6.0, net5.0, netstandard2.0, netstandard2.1
nuget Newtonsoft.Json
restore
> dotnet restore
Determining projects to restore...
Paket version 6.2.1+c82f25d6c324024cbd231df154a447a117c2546e
The last restore is still up to date. Nothing left to do.
Total time taken: 0 milliseconds
Paket version 6.2.1+c82f25d6c324024cbd231df154a447a117c2546e
Starting restore process.
Total time taken: 0 milliseconds
Restored E:\techtalk\20210217_offlineapp\samples\CSharpConsoleWithPaket\CSharpConsole\CSharpConsole.csproj (in 125 ms).
cache
nupkgs
添加cache
locations:
source https://api.nuget.org/v3/index.json
cache ./nuget-packages-cache
storage: none
framework: net6.0, net5.0, netstandard2.0, netstandard2.1
nuget Newtonsoft.Json
运行
./.paket/paket.exe install
现在可以再尝试一下离线测试:
- 断网
- 清缓存
dotnet nuget locals all -c
- 删除
paket-files
; - 运行
dotnet restore