nixpkgs mirror (for testing)
github.com/NixOS/nixpkgs
nix
1# Dotnet {#dotnet}
2
3## Local Development Workflow {#local-development-workflow}
4
5For local development, it's recommended to use nix-shell to create a dotnet environment:
6
7```nix
8# shell.nix
9with import <nixpkgs> {};
10
11mkShell {
12 name = "dotnet-env";
13 packages = [
14 dotnet-sdk
15 ];
16}
17```
18
19### Using many sdks in a workflow {#using-many-sdks-in-a-workflow}
20
21It's very likely that more than one sdk will be needed on a given project. Dotnet provides several different frameworks (E.g dotnetcore, aspnetcore, etc.) as well as many versions for a given framework. Normally, dotnet is able to fetch a framework and install it relative to the executable. However, this would mean writing to the nix store in nixpkgs, which is read-only. To support the many-sdk use case, one can compose an environment using `dotnetCorePackages.combinePackages`:
22
23```nix
24with import <nixpkgs> {};
25
26mkShell {
27 name = "dotnet-env";
28 packages = [
29 (with dotnetCorePackages; combinePackages [
30 sdk_6_0
31 sdk_7_0
32 ])
33 ];
34}
35```
36
37This will produce a dotnet installation that has the dotnet 6.0 7.0 sdk. The first sdk listed will have it's cli utility present in the resulting environment. Example info output:
38
39```ShellSession
40$ dotnet --info
41.NET SDK:
42 Version: 7.0.202
43 Commit: 6c74320bc3
44
45Środowisko uruchomieniowe:
46 OS Name: nixos
47 OS Version: 23.05
48 OS Platform: Linux
49 RID: linux-x64
50 Base Path: /nix/store/n2pm44xq20hz7ybsasgmd7p3yh31gnh4-dotnet-sdk-7.0.202/sdk/7.0.202/
51
52Host:
53 Version: 7.0.4
54 Architecture: x64
55 Commit: 0a396acafe
56
57.NET SDKs installed:
58 6.0.407 [/nix/store/3b19303vwrhv0xxz1hg355c7f2hgxxgd-dotnet-core-combined/sdk]
59 7.0.202 [/nix/store/3b19303vwrhv0xxz1hg355c7f2hgxxgd-dotnet-core-combined/sdk]
60
61.NET runtimes installed:
62 Microsoft.AspNetCore.App 6.0.15 [/nix/store/3b19303vwrhv0xxz1hg355c7f2hgxxgd-dotnet-core-combined/shared/Microsoft.AspNetCore.App]
63 Microsoft.AspNetCore.App 7.0.4 [/nix/store/3b19303vwrhv0xxz1hg355c7f2hgxxgd-dotnet-core-combined/shared/Microsoft.AspNetCore.App]
64 Microsoft.NETCore.App 6.0.15 [/nix/store/3b19303vwrhv0xxz1hg355c7f2hgxxgd-dotnet-core-combined/shared/Microsoft.NETCore.App]
65 Microsoft.NETCore.App 7.0.4 [/nix/store/3b19303vwrhv0xxz1hg355c7f2hgxxgd-dotnet-core-combined/shared/Microsoft.NETCore.App]
66
67Other architectures found:
68 None
69
70Environment variables:
71 Not set
72
73global.json file:
74 Not found
75
76Learn more:
77 https://aka.ms/dotnet/info
78
79Download .NET:
80 https://aka.ms/dotnet/download
81```
82
83## dotnet-sdk vs dotnetCorePackages.sdk {#dotnet-sdk-vs-dotnetcorepackages.sdk}
84
85The `dotnetCorePackages.sdk_X_Y` is preferred over the old dotnet-sdk as both major and minor version are very important for a dotnet environment. If a given minor version isn't present (or was changed), then this will likely break your ability to build a project.
86
87## dotnetCorePackages.sdk vs dotnetCorePackages.runtime vs dotnetCorePackages.aspnetcore {#dotnetcorepackages.sdk-vs-dotnetcorepackages.runtime-vs-dotnetcorepackages.aspnetcore}
88
89The `dotnetCorePackages.sdk` contains both a runtime and the full sdk of a given version. The `runtime` and `aspnetcore` packages are meant to serve as minimal runtimes to deploy alongside already built applications.
90
91## Packaging a Dotnet Application {#packaging-a-dotnet-application}
92
93To package Dotnet applications, you can use `buildDotnetModule`. This has similar arguments to `stdenv.mkDerivation`, with the following additions:
94
95* `projectFile` is used for specifying the dotnet project file, relative to the source root. These have `.sln` (entire solution) or `.csproj` (single project) file extensions. This can be a list of multiple projects as well. When omitted, will attempt to find and build the solution (`.sln`). If running into problems, make sure to set it to a file (or a list of files) with the `.csproj` extension - building applications as entire solutions is not fully supported by the .NET CLI.
96* `nugetDeps` takes either a path to a `deps.nix` file, or a derivation. The `deps.nix` file can be generated using the script attached to `passthru.fetch-deps`. If the argument is a derivation, it will be used directly and assume it has the same output as `mkNugetDeps`.
97::: {.note}
98For more detail about managing the `deps.nix` file, see [Generating and updating NuGet dependencies](#generating-and-updating-nuget-dependencies)
99:::
100
101* `packNupkg` is used to pack project as a `nupkg`, and installs it to `$out/share`. If set to `true`, the derivation can be used as a dependency for another dotnet project by adding it to `projectReferences`.
102* `projectReferences` can be used to resolve `ProjectReference` project items. Referenced projects can be packed with `buildDotnetModule` by setting the `packNupkg = true` attribute and passing a list of derivations to `projectReferences`. Since we are sharing referenced projects as NuGets they must be added to csproj/fsproj files as `PackageReference` as well.
103 For example, your project has a local dependency:
104 ```xml
105 <ProjectReference Include="../foo/bar.fsproj" />
106 ```
107 To enable discovery through `projectReferences` you would need to add:
108 ```xml
109 <ProjectReference Include="../foo/bar.fsproj" />
110 <PackageReference Include="bar" Version="*" Condition=" '$(ContinuousIntegrationBuild)'=='true' "/>
111 ```
112* `executables` is used to specify which executables get wrapped to `$out/bin`, relative to `$out/lib/$pname`. If this is unset, all executables generated will get installed. If you do not want to install any, set this to `[]`. This gets done in the `preFixup` phase.
113* `runtimeDeps` is used to wrap libraries into `LD_LIBRARY_PATH`. This is how dotnet usually handles runtime dependencies.
114* `buildType` is used to change the type of build. Possible values are `Release`, `Debug`, etc. By default, this is set to `Release`.
115* `selfContainedBuild` allows to enable the [self-contained](https://docs.microsoft.com/en-us/dotnet/core/deploying/#publish-self-contained) build flag. By default, it is set to false and generated applications have a dependency on the selected dotnet runtime. If enabled, the dotnet runtime is bundled into the executable and the built app has no dependency on .NET.
116* `useAppHost` will enable creation of a binary executable that runs the .NET application using the specified root. More info in [Microsoft docs](https://learn.microsoft.com/en-us/dotnet/core/deploying/#publish-framework-dependent). Enabled by default.
117* `useDotnetFromEnv` will change the binary wrapper so that it uses the .NET from the environment. The runtime specified by `dotnet-runtime` is given as a fallback in case no .NET is installed in the user's environment. This is most useful for .NET global tools and LSP servers, which often extend the .NET CLI and their runtime should match the users' .NET runtime.
118* `dotnet-sdk` is useful in cases where you need to change what dotnet SDK is being used. You can also set this to the result of `dotnetSdkPackages.combinePackages`, if the project uses multiple SDKs to build.
119* `dotnet-runtime` is useful in cases where you need to change what dotnet runtime is being used. This can be either a regular dotnet runtime, or an aspnetcore.
120* `testProjectFile` is useful in cases where the regular project file does not contain the unit tests. It gets restored and build, but not installed. You may need to regenerate your nuget lockfile after setting this. Note that if set, only tests from this project are executed.
121* `disabledTests` is used to disable running specific unit tests. This gets passed as: `dotnet test --filter "FullyQualifiedName!={}"`, to ensure compatibility with all unit test frameworks.
122* `dotnetRestoreFlags` can be used to pass flags to `dotnet restore`.
123* `dotnetBuildFlags` can be used to pass flags to `dotnet build`.
124* `dotnetTestFlags` can be used to pass flags to `dotnet test`. Used only if `doCheck` is set to `true`.
125* `dotnetInstallFlags` can be used to pass flags to `dotnet install`.
126* `dotnetPackFlags` can be used to pass flags to `dotnet pack`. Used only if `packNupkg` is set to `true`.
127* `dotnetFlags` can be used to pass flags to all of the above phases.
128
129When packaging a new application, you need to fetch its dependencies. Create an empty `deps.nix`, set `nugetDeps = ./deps.nix`, then run `nix-build -A package.fetch-deps` to generate a script that will build the lockfile for you.
130
131Here is an example `default.nix`, using some of the previously discussed arguments:
132```nix
133{ lib, buildDotnetModule, dotnetCorePackages, ffmpeg }:
134
135let
136 referencedProject = import ../../bar { /* ... */ };
137in buildDotnetModule rec {
138 pname = "someDotnetApplication";
139 version = "0.1";
140
141 src = ./.;
142
143 projectFile = "src/project.sln";
144 nugetDeps = ./deps.nix; # see "Generating and updating NuGet dependencies" section for details
145
146 projectReferences = [ referencedProject ]; # `referencedProject` must contain `nupkg` in the folder structure.
147
148 dotnet-sdk = dotnetCorePackages.sdk_6_0;
149 dotnet-runtime = dotnetCorePackages.runtime_6_0;
150
151 executables = [ "foo" ]; # This wraps "$out/lib/$pname/foo" to `$out/bin/foo`.
152 executables = []; # Don't install any executables.
153
154 packNupkg = true; # This packs the project as "foo-0.1.nupkg" at `$out/share`.
155
156 runtimeDeps = [ ffmpeg ]; # This will wrap ffmpeg's library path into `LD_LIBRARY_PATH`.
157}
158```
159
160Keep in mind that you can tag the [`@NixOS/dotnet`](https://github.com/orgs/nixos/teams/dotnet) team for help and code review.
161
162## Dotnet global tools {#dotnet-global-tools}
163
164[.NET Global tools](https://learn.microsoft.com/en-us/dotnet/core/tools/global-tools) are a mechanism provided by the dotnet CLI to install .NET binaries from Nuget packages.
165
166They can be installed either as a global tool for the entire system, or as a local tool specific to project.
167
168The local installation is the easiest and works on NixOS in the same way as on other Linux distributions.
169[See dotnet documentation](https://learn.microsoft.com/en-us/dotnet/core/tools/global-tools#install-a-local-tool) to learn more.
170
171[The global installation method](https://learn.microsoft.com/en-us/dotnet/core/tools/global-tools#install-a-global-tool)
172should also work most of the time. You have to remember to update the `PATH`
173value to the location the tools are installed to (the CLI will inform you about it during installation) and also set
174the `DOTNET_ROOT` value, so that the tool can find the .NET SDK package.
175You can find the path to the SDK by running `nix eval --raw nixpkgs#dotnet-sdk` (substitute the `dotnet-sdk` package for
176another if a different SDK version is needed).
177
178This method is not recommended on NixOS, since it's not declarative and involves installing binaries not made for NixOS,
179which will not always work.
180
181The third, and preferred way, is packaging the tool into a Nix derivation.
182
183### Packaging Dotnet global tools {#packaging-dotnet-global-tools}
184
185Dotnet global tools are standard .NET binaries, just made available through a special
186NuGet package. Therefore, they can be built and packaged like every .NET application,
187using `buildDotnetModule`.
188
189If however the source is not available or difficult to build, the
190`buildDotnetGlobalTool` helper can be used, which will package the tool
191straight from its NuGet package.
192
193This helper has the same arguments as `buildDotnetModule`, with a few differences:
194
195* `pname` and `version` are required, and will be used to find the NuGet package of the tool
196* `nugetName` can be used to override the NuGet package name that will be downloaded, if it's different from `pname`
197* `nugetHash` is the hash of the fetched NuGet package. `nugetSha256` is also supported, but not recommended. Set this to `lib.fakeHash` for the first build, and it will error out, giving you the proper hash. Also remember to update it during version updates (it will not error out if you just change the version while having a fetched package in `/nix/store`)
198* `dotnet-runtime` is set to `dotnet-sdk` by default. When changing this, remember that .NET tools fetched from NuGet require an SDK.
199
200Here is an example of packaging `pbm`, an unfree binary without source available:
201```nix
202{ buildDotnetGlobalTool, lib }:
203
204buildDotnetGlobalTool {
205 pname = "pbm";
206 version = "1.3.1";
207
208 nugetHash = "sha256-ZG2HFyKYhVNVYd2kRlkbAjZJq88OADe3yjxmLuxXDUo=";
209
210 meta = {
211 homepage = "https://cmd.petabridge.com/index.html";
212 changelog = "https://cmd.petabridge.com/articles/RELEASE_NOTES.html";
213 license = lib.licenses.unfree;
214 platforms = lib.platforms.linux;
215 };
216}
217```
218## Generating and updating NuGet dependencies {#generating-and-updating-nuget-dependencies}
219
220When writing a new expression, you can use the generated `fetch-deps` script to initialise the lockfile.
221After creating a blank `deps.nix` and pointing `nugetDeps` to it,
222build the script with `nix-build -A package.fetch-deps` and then run the result.
223(When the root attr is your package, it's simply `nix-build -A fetch-deps`.)
224
225There is also a manual method:
226First, restore the packages to the `out` directory, ensure you have cloned
227the upstream repository and you are inside it.
228
229```bash
230$ dotnet restore --packages out
231 Determining projects to restore...
232 Restored /home/lychee/Celeste64/Celeste64.csproj (in 1.21 sec).
233```
234
235Next, use `nuget-to-nix` tool provided in nixpkgs to generate a lockfile to `deps.nix` from
236the packages inside the `out` directory.
237
238```bash
239$ nuget-to-nix out > deps.nix
240```
241Which `nuget-to-nix` will generate an output similar to below
242```nix
243{ fetchNuGet }: [
244 (fetchNuGet { pname = "FosterFramework"; version = "0.1.15-alpha"; hash = "sha256-lM6eYgOGjl1fx6WFD7rnRi/YAQieM0mx60h0p5dr+l8="; })
245 (fetchNuGet { pname = "Microsoft.AspNetCore.App.Runtime.linux-x64"; version = "8.0.1"; hash = "sha256-QbUQXjCzr8j8u/5X0af9jE++EugdoxMhT08F49MZX74="; })
246 (fetchNuGet { pname = "Microsoft.NET.ILLink.Tasks"; version = "8.0.1"; hash = "sha256-SopZpGaZ48/8dpUwDFDM3ix+g1rP4Yqs1PGuzRp+K7c="; })
247 (fetchNuGet { pname = "Microsoft.NETCore.App.Runtime.linux-x64"; version = "8.0.1"; hash = "sha256-jajBI5GqG2IIcsIMgxTHfXbMapoXrZGl/EEhShwYq7w="; })
248 (fetchNuGet { pname = "SharpGLTF.Core"; version = "1.0.0-alpha0031"; hash = "sha256-Bs4baD5wNIH6wAbGK4Xaem0i3luQkOQs37izBWdFx1I="; })
249 (fetchNuGet { pname = "SharpGLTF.Runtime"; version = "1.0.0-alpha0031"; hash = "sha256-TwJO6b8ubmwBQh6NyHha8+JT5zHDJ4dROBbsEbUaa1M="; })
250 (fetchNuGet { pname = "Sledge.Formats"; version = "1.2.2"; hash = "sha256-0Ddhuwpu3wwIzA4NuPaEVdMkx6tUukh8uKD6nKoxFPg="; })
251 (fetchNuGet { pname = "Sledge.Formats.Map"; version = "1.1.5"; hash = "sha256-hkYJ2iWIz7vhPWlDOw2fvTenlh+4/D/37Z71tCEwnK8="; })
252 (fetchNuGet { pname = "System.Numerics.Vectors"; version = "4.5.0"; hash = "sha256-qdSTIFgf2htPS+YhLGjAGiLN8igCYJnCCo6r78+Q+c8="; })
253]
254```
255
256Finally, you move the `deps.nix` file to the appropriate location to be used by `nugetDeps`, then you're all set!
257
258If you ever need to update the dependencies of a package, you instead do
259
260* `nix-build -A package.fetch-deps` to generate the update script for `package`
261* Run `./result` to regenerate the lockfile to the path passed for `nugetDeps` (keep in mind if it can't be resolved to a local path, the script will write to `$1` or a temporary path instead)
262* Finally, ensure the correct file was written and the derivation can be built.