English
Shared build settings
Step 1. One place for the build settings
Why. Every .csproj created by a template repeats the same properties: the target framework, nullable reference types, implicit usings. With seven projects (three now, four test projects later), changing one setting would mean editing seven files and hoping none is forgotten.
MSBuild, the build engine of .NET, automatically imports a file named Directory.Build.props from the project's folder or any folder above it. A file in the repository root therefore applies to every project of the repository.
Do. Create the file in the repository root:
xml
<Project>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<!-- .NET analyzers at the recommended level, plus the IDE style rules from .editorconfig, checked on build. -->
<AnalysisLevel>latest-recommended</AnalysisLevel>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<!-- Restore checks direct and transitive packages against known advisories; with warnings as errors a
vulnerable package fails the build, in CI and in the deploy. -->
<NuGetAudit>true</NuGetAudit>
<NuGetAuditMode>all</NuGetAuditMode>
</PropertyGroup>
<PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'">
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
</PropertyGroup>
</Project>What each setting does:
TargetFrameworknet10.0— the projects run on .NET 10.LangVersion14pins the C# version, so a newer SDK does not silently enable newer language features.Nullableenable— the compiler tracks which references may benull.stringmeans "never null",string?means "may be null", and using astring?without a check gives a warning. MostNullReferenceExceptions become compile-time warnings.ImplicitUsingsenable— common namespaces (System,System.Linq,System.Threading.Tasks, ...) are imported in every file automatically.TreatWarningsAsErrorstrue— every warning fails the build. This sounds harsh, but it is the only way to keep zero warnings: a warning that does not fail anything gets ignored, then there are fifty of them, and the important fifty-first is lost among them.AnalysisLevellatest-recommended— turns on the recommended set of the .NET code analyzers (rulesCA…): wrongasyncusage, missingCancellationToken, culture-dependent string comparison, and many more.EnforceCodeStyleInBuildalso checks the style rules (IDE…) of.editorconfigduring the build, not only in the IDE.NuGetAuditwithNuGetAuditModeall— on restore, NuGet checks every package, including the packages they depend on, against the database of known vulnerabilities. With warnings as errors, a vulnerable package fails the build.ContinuousIntegrationBuild— only on GitHub Actions (the variableGITHUB_ACTIONSistruethere): makes the build output deterministic, independent of the folder it was built in (topic 22).
Now the projects no longer need their own copies. Remove the <PropertyGroup> with TargetFramework, ImplicitUsings and Nullable from each of the three .csproj files. What remains is the SDK and the references:
xml
<Project Sdk="Microsoft.NET.Sdk">
</Project>xml
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Chatex.Data\Chatex.Data.csproj" />
</ItemGroup>
</Project>xml
<Project Sdk="Microsoft.NET.Sdk.Web">
<ItemGroup>
<ProjectReference Include="..\Chatex.Core\Chatex.Core.csproj" />
</ItemGroup>
</Project>Check
dotnet build ends with Build succeeded, 0 Warning(s), 0 Error(s). Now break it on purpose: add these two lines at the top of Source/Chatex.Api/Program.cs:
cs
string? name = null;
Console.WriteLine(name.Length);The build fails with error CS8602: Dereference of a possibly null reference. Without the shared settings this would be a warning that is easy to miss, and a NullReferenceException at run time. Remove the two lines again.
Step 2. Code style rules
Why. The analyzers and the IDE need to know the style of the project: four spaces or tabs, var or explicit types, file-scoped namespaces or blocks, which naming rules apply. The standard place for these settings is .editorconfig in the repository root; Visual Studio, Rider, VS Code and the dotnet format command all read it, so every developer formats code the same way.
Do. The Chatex .editorconfig has more than 400 lines, most of them the defaults written out by the dotnet new editorconfig template. Download it:
powershell
Invoke-WebRequest https://raw.githubusercontent.com/musicvano/Chatex/27c83c6932b902c8d8dcef01e30a3dd32c5be05f/.editorconfig -OutFile .editorconfigOpen it and find the parts that differ from the template. The general rules come first: spaces, LF line endings, two spaces in XML and JSON files:
ini
root = true
# All files
[*]
indent_style = space
end_of_line = lf
# Xml files
[*.xml]
indent_size = 2
# ...At the end, a few analyzer rules are switched off on purpose, each with its reason:
ini
# EF Core migrations are generated; analyzers skip them.
[Source/Chatex.Data/Migrations/**.cs]
generated_code = true
# Analyzer rules turned off on purpose (AnalysisLevel latest-recommended in Directory.Build.props).
[*.cs]
# CA1716: Error and Result are C#-only types; VB keyword clashes do not matter here.
dotnet_diagnostic.CA1716.severity = none
# CA1000: Result<T> exposes static factory members and implicit conversions by design.
dotnet_diagnostic.CA1000.severity = none
# Test names read as sentences (Login_locks_the_account_after_five_wrong_passwords).
[Tests/**.cs]
dotnet_diagnostic.CA1707.severity = noneSwitching a rule off is a decision, so it is written down with the reason, in the one place where everyone sees it. Never switch off a warning just to make the build pass without understanding it.
On Windows the dotnet new templates wrote their files with CR LF line endings, which the new rule end_of_line = lf rejects. Let dotnet format bring the code to the style of .editorconfig once:
powershell
dotnet format Chatex.slnxCheck
powershell
dotnet format Chatex.slnx --verify-no-changesThe command finishes without output: the code matches the style. Without the previous command it would report error ENDOFLINE: Fix end of line marker for every line of Program.cs. CI runs the same check on every push (topic 22), and dotnet format Chatex.slnx is the command to run whenever it complains.
The other files with CR LF
dotnet format fixes only C# files. The .csproj and JSON files created by the templates still have CR LF in your folder, but .gitattributes stores them with LF when you add them (git add warns that "CRLF will be replaced by LF"), so the repository is consistent.
Step 3. Central package management
Why. Chatex uses about 25 NuGet packages. If every project writes the version of each package it uses, the versions drift apart: the data layer uses EF Core 10.0.14 and a test project 10.0.12, and the two clash at run time. Central Package Management (CPM) moves all versions into one file, Directory.Packages.props in the repository root; a project then references a package by name only.
Do. Create the file with the versions of every package the tutorial uses. Most of them are not needed yet; a version that no project references does nothing, and listing them now means you never have to look for a matching version later.
xml
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="EFCore.NamingConventions" Version="10.0.1" />
<PackageVersion Include="FluentValidation" Version="12.2.0" />
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.14" />
<PackageVersion Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.14" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.14" />
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.14" />
<PackageVersion Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.14" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.Configuration" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.Configuration.Abstractions" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.Options.DataAnnotations" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.11.0" />
<PackageVersion Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.23.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
<PackageVersion Include="Respawn" Version="7.0.0" />
<PackageVersion Include="Scalar.AspNetCore" Version="2.18.7" />
<PackageVersion Include="Shouldly" Version="4.3.0" />
<PackageVersion Include="Testcontainers.PostgreSql" Version="4.16.0" />
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
<PackageVersion Include="xunit.v3" Version="4.0.2" />
<PackageVersion Include="xunit.v3.extensibility.core" Version="4.0.2" />
</ItemGroup>
</Project>From now on, a package is added to a project with the usual command, for example dotnet add Source/Chatex.Data package Npgsql.EntityFrameworkCore.PostgreSQL. Because the version is already in Directory.Packages.props, the command writes a <PackageReference> without a Version attribute into the project. Updating a package means changing one line in one file.
Do not update the versions in this tutorial
The listings, the tests and the screenshots of the tutorial match these exact versions. Use them as they are; updating packages is a separate task with its own testing (an exercise in the checkpoint of topic 22 shows how CI helps with it).
Check
dotnet build still ends with Build succeeded and zero warnings.