Our first Microservice with .NET Core 3.1–First Part

Elsavies
Proscai X
Published in
7 min readAug 11, 2020

Microservice is a term that is getting more and more attention in the IT world, the main reason for this, is the cost benefits it represents for big companies with old systems based on SOA architecture, it also gives many benefits in Development Time, Automation, System Performance, Scalability and Security.

For this tutorial i will show you, how to create your first Microservice using the .NET Core 3.1 hosted in a Docker Container with a NGinx based Image.

Requirements:

  • Visual Studio 2019
  • Asp.Net and Web Development Extension for Visual Studio 2019
  • .Net Core cross-platform Extension for Visual Studio 2019

Visual Studio NuGet Packages:

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.Relational
  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer | Npgsql.EntityFrameworkCore.PostegreSQL | MySql.Data.EntityFrameworkCore (Your Favorite SQL Database Engine)
  • Microsoft.EntityFrameworkCore.SqlServer.Design | Npgsql.EntityFrameworkCore.PostgreSQL.Design | MySql.Data.EntityFrameworkCore.Design
  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.ConfigurationJson
  • Microsoft.Extensions.Options

Note: If you choose MySql Database Engine, you will need an specific MySQL Connector depending on your MySql Server Version

Before Start

Before beginning developing it is importat to understand SOA Architecture, because, Microservices is an Evolution of SOA, having said that, this is how a normal SOA Architecture looks like:

Windows N-tier application on Azure with SQL Server
Windows N-tier application on Azure with SQL Server

In a SOA architecture you have your System splitted in 4 layers: Access, Services, Business and Data, where traffic from users keep that flow of processing, access layer defines a point where all the user requests(Normally HTTPS requests to Restful/JSon API’s) first come and the packages are validated by the security policies you have stablished in your Web API, if everything goes well, the package is send to the services layer where you request the operations engines needed to the business layer, once the package is in the business layer, the operations access to the data layer and perform the read/write process in the corresponding tables defined in your database schema.

This architecture presents so many problems like coupled functionalities between system, slow time for deployment, error propagations in all the system if just one part failure, and some other problems.

For this reason Microservices architecture was born, in this new architecture, every part of your system is isolated and deployed as an individual service(decoupled in the same 4 layers), presenting a solution for SOA problems mentioned, but at the same time adding more difficulties in the development/implementation/production process, a normal Microservice architecture looks like this:

Building microservices on Azure
Building microservices on Azure

AUTH-DATA

It does not matter what kind of project you will create, normally it will have users interacting on it, for this reason when designing your database model, the first part you should define is your Users, Roles and Permission schema, this is called Identity Database Model, for this, we will use Asp.Net Identity for Entity Framework Core which have so many built-in objects with a lot of really useful functionalities that can save us plenty of time.

In Visual Studio, Create a new proyect, this project should be type of Class Library(Net Core) C#, project name : Auth-Data, and solution name : MyFirstMicroService

Class Library with .Net Core

Create a folder inside your Auth-Data project and name it Entities, inside the folder create the next C# classes:

  • ApplicationUser.cs: Normal user table with some custom fields that we will use later in other tutorials.
ApplicationUser.cs
  • ApplicationRole.cs: Handle all roles of the system.
ApplicationRole.cs
  • ApplicationUserRole.cs: Many to Many relation table for Users-Roles.
ApplicationUserRole.cs
  • ApplicationUserClaim.cs: Handle all user claims.
ApplicationUserClaim.cs
  • ApplicationRoleClaim.cs: Handle all role claims.
ApplicationRoleClaim.cs
  • ApplicationUserLogin.cs: Handle all user logins in the time.
ApplicationUserLogin.cs
  • ApplicationUserToken.cs: Handle all user tokens for ResetPassword and Email Confirmation.
ApplicationUserToken.cs

Now we need to create our database context, in this C# class we are going to specify our database tables and how they relate to each other using code first paradigm, create a new C# class inside your Auth-Data project root directory and name it ApplicationDBContext.cs

  • ApplicationDBContext.cs:
ApplicationDbContext.cs

Now that we have all our entities relations defined in our ApplicationDBContext.cs class, we need to run our first migration with entity framework, by doing this, what we do is to convert our ApplicationDBContext.cs specifications into tables and relations inside our database engine.

First let’s create an appsettings.json for our project, this one will be used by the DotNet EF command in Design Time:

appsettings.json

Use the database engine that you prefer, in this case we will use PostgreSql, now we need to create an ApplicationDbContextFactory.cs class that implements IDesignTimeDbContextFactory.cs Interface, this will be used to run our migration with DotNet runtime framework:

ApplicationDbContextFactory.cs

Now let’s run our first migration, open a Nuget Package Manager Console within your solution in Visual Studio 2019 and type the next:

PM> dotnet ef migrations add InitialMigration -p Auth-Data

If everything goes well, you should see a message like this:

Initial Migration Message

you should also see that a new folder has been created in your project with the name of Migrations:

Project’s new File Structure

Now let’s run a database update command to coordinate your code with your Database Engine database:

PM> dotnet ef database update -p Auth-Data

A new message like this will be shown, where is specified that your last migration were applied to your database, you can do updates and rollbacks to your desired migration:

Database Update Command

Now you can check if the changes were made in your decided Database Engine Administration Panel, in the case of this tutorial you can check it in your PgAdmin 4 V4 Panel:

Database Created in DB Server

AUTH-API

Now create a new project in your Solution and name it Auth-API, the project should be type of ASP.Net Core Web Application:

ASP.NET Core Web Application

Create a new folder and name it Helpers, add a new class inside it and name it AppSettings.cs, put the next code inside:

AppSettings.cs

Now add the next code to the Startup.cs file of your Auth-API project:

Startup.cs

Add appsettings.json file to your project, the action will add appsettings.Development.json as well, add two new overrides for differents environments(appsettings.Stage.json, appsettings.Production.json) that we will use in the next tutorial, add the next to appsettings.Development.json this is the one that will be used by the server when the API is running:

appsettings.Development.json

Add a new folder inside the project and name it Models, inside Models folder add a new folder and name it Requests, add these two classes inside it:

LogInRequestModel.cs:

LoginRequestModel.cs

SignUpRequestModel.cs:

SignUpRequestModel.cs

Add a new folder inside the project and name it Contracts, add a new C# Interface and name it IIdentityAdapter.cs:

IIdentityAdapter.cs

Add a new folder inside the project and name it Adapters, add a new C# class and name it IdentityAdapter.cs, this class will implement the Interface we created in the last step:

IdentityAdapter.cs

Inside the Contracts folder add a new C# Interface and name it IApiResponseModel.cs, put this code inside of it:

IApiResponseModel.cs

Inside the Models folder, add a new folder and name it Results, add a new class inside of it and name it ApiResponseModel.cs, this class will implement the interface created in the last step:

ApiResponseModel.cs

In this last step, add a new folder inside the project and name it Controllers, add a new C# class inside of it and name it accountController.cs, put this code inside of it:

AccountController.cs

If you have followed all the steps until this point, you should have the next solution structure:

MyFirstMicroservice Solution Structure

Now just hit F5 and see your first microservice running, enter to the Swagger UI Panel, https://localhost:[yourport]/swagger, you should see something like this:

Swagger UI for API’s

Swagger UI shows all the http methods in your API, the schemas that every method uses and the URI paths to the methods, as well as other good information.

Other Approachs:

  • This approach is independent from the cloud, but if you desire to use Azure Cloud, a better aproach that includes federation identity, OpenID Connect and OAuth 2.0 standards is Azure Active Directory Auth, it also has solutions for B2B and B2C(50k users for free) that are really easy to implement in your code.
  • Another good aproach to handle identity systems independently from the cloud provider is Identity Server 4, it also gives you OpenID Connect and OAuth 2.0 standards.

To avoid making this tutorial bigger, Follow Me and wait for the next part:

“Containerizing your First MicroService with Docker and creating CI/CD Pipelines with Jenkins — Second Part”

Finally you can download this tutorial from my GitHub Account: Elsavies

Follow me as well in Facebook and Instagram :)

--

--

Elsavies
Proscai X

Software Architect, Passionate Gamer, IT Lover