Search code examples
c#msbuild.net-6.0visual-studio-2022

VS2022 Adding prefix to default namespace for whole solution


I have a .NET 6 VS2022 c# solution, where each project has a default namespace set as $(MSBuildProjectName.Replace(" ", "_")) - see project -> properties -> DefaultNamespace -> its automatically set by project template. What I would like to do is to have a prefix for namespaces in every project part of this solution.

So, something like this:

<RootNamespace>MyCompany.MyProject.$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace>

I can do this for each project manually, but what I would like to do is, to have some global variable on solution level, where I could set two vairables:

<CompanyName>MyCompany</CompanyName>
<ProjectName>MyProject</ProjectName>

Which would result in

$(MyCompany).$(MyProject).$(MSBuildProjectName.Replace(" ", "_"))

This solution should also be compatible with dotnet build procedure and docker-compose, so that it does not break any of them. In a nutshell, with these variables user should still be able to clone git repository on a brand new pc, and build the project without any extra work.

Any ideas? I read that you can create a solution props file where you can define variables, but looks like its a C++ specific?


Solution

  • The project files are MSBuild. You can add custom MSBuild to all your projects with Directory.Build.props and Directory.Build.targets files.

    In the root of your code tree (or a directory in your code tree that contains all of the relevant projects) create a file named Directory.Build.targets. Each project when run, searches up the directory hierarchy looking for a file named Directory.Build.targets. If such a file is found, it is automatically imported.

    Place your properties and property re-definitions in the Directory.Build.targets file.

    Example:

    <Project>
      <PropertyGroup>
        <!-- Custom Properties -->
        <CompanyName>MyCompany</CompanyName>
        <ProjectName>MyProject</ProjectName>
        <!-- Redefine MSBuild Properties -->
        <Company>$(CompanyName)</Company>
        <RootNamespace>$(CompanyName).$(ProjectName).$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace>
      </PropertyGroup>
    </Project>
    

    A better organization if you are likely to have a lot of customizations would be to place the custom properties in the .props file and the redefinitions in the .targets file.

    Directory.Build.props and Directory.Build.targets were added in MSBuild v15 and are not language specific. In the MSBuild documentation, see Customize your build.

    For the Company property see Assembly attribute properties.