Skip to content

Creating dotnet microservice

Aron Heesakkers edited this page Apr 23, 2021 · 16 revisions

Create a .NET Microservice

For consistency the process of creating new microservices is streamlined in this protocol.

Table of Contents

Table of contents generated with markdown-toc

Github Repo

Go to the organisation and create a new repo in kebab-case.

Example: tree-service

Step 1

Add a gnu v3 license.

Step 2

Add a README.md

Step 3

Go to www.gitignore.io and type:

  • macOS
  • VisualStudio
  • Intellij

Step 4

Next click create and copy the contents of the file. Paste these contents in the .gitignore of your repository.

Pull repo

Pull the repository in with your favourite git tool (ie. Git Bash, Git kraken, Github Desktop)

Create a new ASP .NET Core Web API project and name this project the same as your repository.

Choose the options:

Option Value
Solution and project in same directory Yes
Authentication Type No.
Target Framework CORE 3.1
Configure for HTTPS No
Enable for Docker No

After this project is created, move the contents of your project to your repository root.

- tree-service\
  .gitignore
  README.md
  - Controllers
  - Properties
  .appsettings.json
  ...

Choose port

Go to our wiki to check which ports are not in use and choose the number following the one of the last microservice.
Example:

  • If the last microservice uses 5030 use 5031 and update the documentation in the wiki.l

Docker

Create a new file named Dockerfile. This will be used in production.

  • Note:
    • Replace tree-service with your own service name.
    • Replace the port number with your own port number.
FROM mcr.microsoft.com/dotnet/aspnet:3.1 AS base
WORKDIR /app
EXPOSE 5002

FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
ENV ASPNETCORE_ENVIRONMENT="Production"
ENV ENVIRONMENT="Production"

WORKDIR /src
COPY ["tree-service.csproj", "."]
RUN dotnet restore "./tree-service.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "tree-service.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "tree-service.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "tree-service.dll"]

Next create a file named Dockerfile.local. This will be used in development.

  • Note:
    • Replace tree-service with your own service name
    • Replace the port number with your own port number.
FROM mcr.microsoft.com/dotnet/aspnet:3.1 AS base
WORKDIR /app
EXPOSE 5002

FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
ENV ASPNETCORE_ENVIRONMENT="Development"
ENV ENVIRONMENT="Development"

WORKDIR /src
COPY ["tree-service.csproj", "."]
RUN dotnet restore "./tree-service.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "tree-service.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "tree-service.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "tree-service.dll"]

Use new port

Go to Program.cs and change the port to your port number.

Example:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                    .UseUrls("http://*:5003"); //Add this line
                });

CORS Settings

In Startup.cs add this line.

readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

In ConfigureServices() add

services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                      builder =>
                      {
                          builder.WithOrigins("*")
                          .AllowAnyHeader()
                          .AllowAnyMethod()
                          .AllowAnyOrigin();
                      });
            });

In the method Configure() add this line above app.useRouting()

 app.UseCors(MyAllowSpecificOrigins);

Swagger (Optional)

Step 1

Add the following NuGet Package

Swashbuckle.AspNetCore

Step 2

Go to Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(); // Add this line.
...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
     // Add these lines.
     app.UseSwagger(c =>
     {
         c.SerializeAsV2 = true;
     });

     // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
     // specifying the Swagger JSON endpoint.
     app.UseSwaggerUI(c =>
     {
         c.SwaggerEndpoint("/swagger/v1/swagger.json", "personeel-service");
         // Serve the swagger UI at the app's root
         c.RoutePrefix = string.Empty;
     });
...

Allowed Hosts

[Needs implementation]

Add a database

If you don't need a database you can skip this step.

Install Packages

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools

Connection

Add connection string in the root of appsettings.Development.json

{
  "AllowedHosts": "*",
  "ConnectionString": "Server=db;Database=tree_db;User=sa;Password=Your_password123;",
  ...
}

And add the connection string in appsettings.json, but leave this one empty. This empty string will be replaced in the release pipeline.

{
  "AllowedHosts": "*",
  "ConnectionString": "Server=db;Database=main;User=sa;Password=Your_password123;",
   ...
}

Use the connection

In Startup.cs replace TreeContext with your own context.

public void ConfigureServices(IServiceCollection services) 
{
    var connection = Configuration.GetValue<string>("ConnectionString"); // Add this line
    services.AddDbContext<TreeContext>(
          options => options.UseSqlServer(connection)); // Add this line; this registers the TreeContext Dependency
...

Inject YourContext dependency in the constructor and migrate the database.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, TreeContext context) 
{
    context.Database.Migrate();
...

Docker Compose

Create a new file named docker-compose.yml.

  • Note:
    • Replace tree-service with your own service name
    • Replace the port number with your own port number.
version: "3.9"
services:
    pkg:
        build: 
            context: .
            dockerfile: Dockerfile.local
        container_name: tree-service
        ports:
            - "0.0.0.0:5002:5002"
        depends_on:
            - db
        networks: 
            - ipost-network
    db:
        image: "mcr.microsoft.com/mssql/server"
        volumes:
          - sqlvolume:/var/opt/mssql

        environment:
            SA_PASSWORD: "Your_password123"
            ACCEPT_EULA: "Y"
        ports:
            - "0.0.0.0:1433:1433"
        networks: 
            - ipost-network
volumes:
  sqlvolume:

networks:
    ipost-network:
        external: true

Done

Congratulations you are finished!🚀🚀

Clone this wiki locally