How to use Global Usings (introduced in #C 10)?
With the introduction of global usings statements in .NET 6 / C# 10, it’s easier to include frequently used namespaces in your project. You can consolidate all the repetitive using namespaces at the top of many source code files into a single file, and these namespaces will be automatically available for use throughout the entire project. This is a simple and convenient feature that can save time and improve the readability of your code.
For example, if you frequently use methods from the System.IO namespace in your code throughout the project, you could add a global using System.IO; statement to the GlobalUsings.cs file. This would allow you to use methods from the System.IO namespace without having to fully qualify them every time, like this:
global using System.IO;If you have a solution with many projects, you can add your project namespaces to the GlobalUsings.cs. Here is an example:
// vendor, 3th party namespaces
global using System.IO;
global using Microsoft.AspNetCore.Builder;
global using Microsoft.AspNetCore.Hosting;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
// your project namesapces
global using MyMultiProjecsSolution.Application;
global using MyMultiProjecsSolution.Infrastructure.Persistence;
global using MyMultiProjecsSolution.Infrastructure.Persistence.Contexts;
global using MyMultiProjecsSolution.Infrastructure.Shared;
global using MultiProjecsSolution.WebApi.Extensions;
Unlike Program.cs, the GlobalUsings.cs file is optional, and the file is not created by default in a new .NET project. Many developers use the naming convention GlobalUsings.cs and place this file at the root of the project. There is no limit to how many “global using” statements you can include in the GlobalUsings.cs file, but it’s generally a good idea to keep the list of global usings statements concise and only include the namespaces that you will be using frequently in your code.
