The purpose of this document is to provide a step-by-step guide for a developer to setup CI (Continuous Integration) in their .NET projects. This document provides support to both modern .NET (Core and beyond) and .NET Framework too.
The scope of this document covers the following
- Setting up the YAML required to enable document for Gitlab’s CI.
- Configuring the repo to enable CI.
- Testing the CI pipeline.
- If Gitlab is managed by your organization, ensure that CI runner is configured to build .NET applications by the IT team of the organization.
- A GitLab account with access to your target repository.
- A .NET application repository on Gitlab.
- The projects has to be setup with EditorConfig for catching issues related to linting and code analysis.
- Navigate to the .NET application repository on Gitlab.
- Create a file named
.gitlab-ci.yml
in the root directory.
We will need to setup one stage for .NET core projects. The name of this stage should be build
. Set the variable of the DOTNET_VERSION
targeting the version of .NET your application is using.
stages:
- build
variables:
DOTNET_VERSION: "7.0.x"
build:
stage: build
tags:
- ".NET Core"
image: mcr.microsoft.com/dotnet/sdk:$DOTNET_VERSION
script:
- dotnet restore
- dotnet build --no-restore
We need to setup two stages to setup CI for projects built using .NET Framework.
build
stageformat
stage
stages:
- build
- format
build:
stage: build
tags:
- ".NET Framework"
script:
- "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe"
format:
stage: format
tags:
- ".NET Framework"
script:
- "dotnet format --report msbuild ConsoleApp1.csproj"
- $format_file_content = Get-Content "msbuild\format-report.json" -raw
- if ($format_file_content -eq "[]") { exit 0 } else { exit 1 }
Once the YAML file is setup and the Gitlab CI runner functioning properly, the builds should happen on every commit to the repository. As shown in the image.
In the repository, go to Settings > Merge Requests > Merge Checks and check the box as in the image. This will enable pre-check on the pull requests. Everytime a PR is ready to be merged, a build pipeline is invoked to run the CI tasks.
Setting up a CI pipeline for your .NET application offers several benefits:
- Improved code quality through automated linting.
- Consistent and reliable builds.
- Early detection of errors and issues.
- Streamlined collaboration through automated testing of merge requests.
Consider enhancing your CI pipeline by adding additional stages such as unit testing, integration testing, and deployment to further improve the quality and reliability of your .NET application.