📅 July 12, 2023

Using Directory.Build.props & Directory.Packages.props to enable Central Package Management

What is a Directory.Build.props file?

A Directory.Build.props file can reside in the root directory of your .NET project and contain properties that will get applied to every project in the solution. It is useful for enforcing project standards in one spot without needing to configure each project.

An example of a Directory.Build.props is below


The property I want to highlight in this post is ManagePackageVersionsCentrally. This comes into play with the second file I want to discuss, Directory.Packages.props. Setting ManagePackageVersionsCentrally to true and creating a Directory.Packages.props file will enable Central Package Management.

What is Central Package Management? What is a Directory.Packages.props file?

Central Package Management enables you to review and manage your NuGet dependencies in one file, Directory.Packages.props. This is useful if you have many .NET projects in one solution. Using a Directory.Packages.props file allows you to set a version number once for a NuGet dependency. .NET projects downstream can include the dependency, but will not specify a version number. The project(s) will use the version specified in the Directory.Packages.props file.

Another advantage of Directory.Packages.props is for including Roslyn analyzers. You can set a GlobalPackageReference which is used to specify that the dependency will be used by every project. A sample Directory.Packages.props file might look like the following:

    <GlobalPackageReference Include="IDisposableAnalyzers" Version="4.0.6" PrivateAssets="All" IncludeAssets="Runtime;Build;Native;contentFiles;Analyzers" />
    <PackageVersion Include="FluentValidation" Version="11.5.2" />
    <PackageVersion Include="Polly" Version="7.2.4" />

In the above example, IDisposableAnalyzers is included as a GlobalPackageReference which will make it available for all projects. FluentValidation and Polly are included as a PackageVersion and specify a version. Projects can then include a package using the syntax: <PackageReference Include="FluentValidation" />. Now, when you update the version of a NuGet package in Directory.Packages.props, the dependency will be updated for any project downstream!

# development | dotnet