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
- Make the project name as short as possible.
- Ensure the filename of the built assembly doesn't change.
- 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:
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:
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.
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.