iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🎃

Automatically Adding Global Usings via .NET NuGet Packages

に公開

Introduction

The ImplicitUsings feature was added in C# 10.0.

For example, packages frequently used in ASP.NET projects can now be used without explicit using declarations.

In this article, I will show how to automatically add arbitrary global usings to a consumer project through your own NuGet package.

Purpose

Suppose you want to publish extension methods frequently used throughout a system as a NuGet package. For instance, I don't really like code like this:

static void Foo(IEnumerable<int> values)
{
    if (values.Any() is false)
    {
        Console.WriteLine("Hello, Global Usings!");
    }
}

I want to write it like this:

static void Foo(IEnumerable<int> values)
{
    if (values.Empty())
    {
        Console.WriteLine("Hello, Global Usings!");
    }
}

Therefore, I often create extension methods like the following:

namespace Extensions;

public static class EnumerableExtensions
{
    public static bool Empty<T>(this IEnumerable<T> enumerable)
    {
        return enumerable.Any() is false;
    }
}

This in itself is fine, but the namespaces for extension methods can be obscure, and it's common to get lost when you want to use them. In such cases, it's very convenient if a global using is automatically added when the package is referenced.

Steps

Create .props

Add a text file named "ProjectName.props" to the class library project where the extension methods are defined. In the previous example, the filename would be Extensions.props.

Then, write the following content:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <ItemGroup>
    <Using Include="Extensions" />
  </ItemGroup>

</Project>

By including this in the NuGet package, the global using will be automatically added to the consumer project.

Include .props in the package

Add the following description to the .csproj file of the class library project.

  <ItemGroup>
    <!-- Only for .NET 6, default implicit Using. -->
    <None Include="Extensions.props" Pack="true" PackagePath="build" />
  </ItemGroup>

Extensions.props will now be included in the build folder of the NuGet package.

All that's left is to create the package.

That's all.

Discussion