Home > Software engineering >  CrossProject global using in C#
CrossProject global using in C#

Time:12-26

I am refactoring some of my code now that C#10 is in place. I noticed that the amount of references is insane. For that reason, I thought to refactor everything that is shared across every single project into one "shared one" using global usings, but it is not working as expected.

Just for the "minimal" example.

I have one class library that configures API configuration (middlewares and so on). Then I have other few libraries.

The key here is that I would like to have one single library called "setup" which references all the other libraries and, using "global usings", be able to import that library in the webapplications that contains all the domain logic

But, when I create a file in the new setup project with global using Shared.API.xxx seems not to do anything.

I also imported in the webapplication the setup project doing the next:

  <ItemGroup>
    <Using Include="Shared.Setup" />
  </ItemGroup>

Is this possible to do crossproject global usings?

Note: When I import global using Shared.API.xxx anywhere inside the webapplication works as expected.

CodePudding user response:

As docs state - global usings are constrained to the files in compilation (project):

Adding the global modifier to a using directive means that using is applied to all files in the compilation (typically a project).

And imagine imports pollution if you could introduce transitive global usings.

But you can share global using for example by adding them manually as a link to every project:

  • In VS - right click on target project -> Add -> Existing Item but instead of clicking "Add" click on the dropdown arrow to the right and select "Add As Link"
  • Or manually editing the .csproj by adding next:
<ItemGroup>
    <Compile Include="Relative_Path_To_Shared.Setup.SharedUsingsFile.cs" Link="SharedUsingsFile.cs" />
</ItemGroup>
  • Related