Codementor Events

Lets fix your C# project structure!

Published Feb 16, 2020
Lets fix your C# project structure!

I'm going to show you how to use a Directory.Build.props file to clean up your project structure. We will have 3 objectives

  1. Make the project name as short as possible.
  2. Ensure the filename of the built assembly doesn't change.
  3. Ensure the default namespace for new classes doesn't change.

Today we are going to look at your filenames and folder-structure. But before we do, what is a Directory.Build.props? Basically, when a .NET project file (e.g. a .csproj file for C#) gets built, MSBuild will automatically look in the folder, and it's parents, for a file called Directory.Build.props or Directory.Build.targets. If it finds one it will merge it into the very top (or very bottom if it's a .targets file). This allows you to easily share project configuration across all projects in a solution.

So, consider a calculator REST API, for a company called Contoso. A typical project structure will look like this:
Solution1.PNG

As you can see, there is a lot of repetition here. The company name (Contoso) and the solution (Calculator) are repeated on almost every project. If we look at the folder structure, we can see the same problem:

Solution2.PNG

So how do we fix it? First, create a file called Directory.Build.props in the solution folder, containing the following code:

<Project>
  <PropertyGroup Label="Configure assembly names and namespaces">
    <AssemblyName>$(SolutionName).$(MSBuildProjectName)</AssemblyName>
    <RootNamespace>$(AssemblyName)</RootNamespace>
  </PropertyGroup>
</Project>

Then remove Contoso.Calculator from every project file, and every time it appears in the solution file.

At this point, you will have a nice, neat project structure, but the filename of the built assembly, and the default namespace will still be Contoso.Calculator.RestApi.

Solution3.PNG

In the future we will make our stack-traces simpler, set defaults for relevant properties, and activate SourceLink, but that is a story for another time.

Discover and read more posts from Rowland Banks
get started
post commentsBe the first to share your opinion
Show more replies