Creating .Net Core Projects with the CLI
By Harry Bellamy
- 2 minutes read - 305 wordsOne of the key features that was added in .Net Core was the CLI.
The functionality of the CLI we’re going to focus on here is the ability to create new .Net projects.
Bootstrapping a Basic Project Structure
Consider a basic console app. For this application we might want to have two separate projects:
- A console app project to hold all the logic.
- A test project to test the logic in the console app project.
Create the Console App Project
We can first script the console app using dotnet new
like so:
dotnet new console -n MyNewConsoleApp
The -n
argument indicates the name of the project.
Running this command creates a console app project (.csproj) in a new directory with the same name as the name supplied (in the case of the example MyNewConsoleApp
).
Create the Test Project
Next we can create the test project:
dotnet new xunit -n MyNewConsoleApp.Tests
This creates a new xUnit test project with the necessary NuGet package references to run xUnit tests out of the box.
Templates are also available for NUnit (dotnet new nunit
) and MSTest (dotnet new mstest
).
Linking the Two Projects
At this point the unit test project will still be unable to run any tests against the console app project as there is no project reference. Fortunately adding a project reference is also something the .Net CLI can do:
dotnet add MyNewConsoleApp.Tests/MyNewConsoleApp.Tests.csproj reference MyNewConsoleApp/MyNewConsoleApp.csproj
Creating a Reusable Script
We can combine these commands into a parameterised script to create a reusable script to bootstrap a new console app project with this structure:
param (
[Parameter(Mandatory=$true)]
[string] $appName)
dotnet new console -n $appName
$testProjectName = "${appName}.Tests"
dotnet new xunit -n $testProjectName
dotnet add "${testProjectName}/${testProjectName}.csproj" reference "${appName}/${appName}.csproj"
This script can be extended as necessary - e.g. to add additional projects or to add a top-level solution (.sln) file.