Microservices

Spread the love

Microservices

The term microservices portrays a software development style that has grown from contemporary trends to set up practices that are meant to increase the speed and efficiency of developing and managing software solutions at scale. Microservices is more about applying a certain number of principles and architectural patterns as architecture. Each microservice lives independently, but on the other hand, also all rely on each other. All microservices in a project get deployed in production at their own pace, on-premise on the cloud, independently, living side by side.

In this article, we will learn the concept of Microservices, their architecture, and how to create microservices in .NET and C#. You will also learn steps to build, deploy, and test microservices in .NET using a docker container.

Microservices Architecture

The following picture from Microsoft Docs shows the microservices architecture style.

There are various components in a microservices architecture apart from microservices themselves.

Management. Maintains the nodes for the service.

Identity Provider. Manages the identity information and provides authentication services within a distributed network.

Service Discovery. Keeps track of services and service addresses and endpoints.

API Gateway. Serves as client’s entry point. Single point of contact from the client which in turn returns responses from underlying microservices and sometimes an aggregated response from multiple underlying microservices.

CDN. A content delivery network to serve static resources for e.g. pages and web content in a distributed network

Static Content The static resources like pages and web content

Microservices are deployed independently with their own database per service so the underlying microservices look as shown in the following picture.

Monolithic vs Microservices Architecture

Monolithic applications are more of a single complete package having all the related needed components and services encapsulated in one package.

Following is the diagrammatic representation of monolithic architecture being package completely or being service based.

Microservice is an approach to create small services each running in their own space and can communicate via messaging. These are independent services directly calling their own database.

Following is the diagrammatic representation of microservices architecture.

In monolithic architecture, the database remains the same for all the functionalities even if an approach of service-oriented architecture is followed, whereas in microservices each service will have its own database.

Docker Containers and Docker installation

Containers like Dockers and others slice the operating system resources, for e.g. the network stack, processes namespace, file system hierarchy and the storage stack. Dockers are more like virtualizing the operating system. Learn more about dockers here. Open this URL and click on Download from Docker hub. Once downloaded, login to the Docker and follow instructions to install Docker for Windows.

Microservice using ASP.NET Core

This section will demonstrate how to create a Product microservice using ASP.NET Core step by step with the help of pictures. The service would be built using ASP.NET Core 2.1 and Visual Studio 2017. Asp.NET Core comes integrated with VS 2017. This service will have its own DBcontext and database with the isolated repository so that the service could be deployed independently.

Creating an ASP.NET Core Application Solution

Choose the application as ASP.NET Core Web Application and give it a meaningful name.

Next, choose API as the type of the project and make sure that “Enable Docker Support” option is selected with OS type as Linux.

The solution will look as shown below.

Adding Models

Add a new folder named “Model” to the project

In the Models folder, add a class named Product.

Add a few properties like Id, Name, Description, Price to the product class. The product should also be of some kind and for that, a category model is defined and a CategoryId property is added to the product model.

Similarly, add Category model.

Enabling EF Core

Though .NET Core API project has inbuilt support for EF Core and all the related dependencies are downloaded at the time of project creation and compilation that could be found under SDK section in the project as shown below.

Microsoft.EntityFrameworkCore.SqlServer (2.1.1) should be the package inside the downloaded SDK’s. If it is not present, it could be explicitly added to the project via Nuget Packages.

Adding EF Core DbContext

Add a new folder named DBContexts to the project.

Add a new class named ProductContext which includes the DbSet properties for Products and Categories. OnModelCreating is a method via which the master data could be seeded to the database. So, add the OnModelCreating method and add some sample categories that will be added to the database initially into the category table when the database is created.

ProductContext code

  1.  
  2. using Microsoft.EntityFrameworkCore;
  3. using ProductMicroservice.Models;
  4. namespace ProductMicroservice.DBContexts
  5. {
  6.   public class ProductContext : DbContext
  7.   {
  8.     public ProductContext(DbContextOptions<ProductContext> options) : base(options)
  9.     {
  10.     }
  11.     public DbSet<Product> Products { get; set; }
  12.     public DbSet<Category> Categories { get; set; }
  13.  
  14.     protected override void OnModelCreating(ModelBuilder modelBuilder)
  15.     {
  16.       modelBuilder.Entity<Category>().HasData(
  17.           new Category
  18.           {
  19.             Id = 1,
  20.             Name = “Electronics”,
  21.             Description = “Electronic Items”,
  22.           },
  23.           new Category
  24.           {
  25.             Id = 2,
  26.             Name = “Clothes”,
  27.             Description = “Dresses”,
  28.           },
  29.           new Category
  30.           {
  31.             Id = 3,
  32.             Name = “Grocery”,
  33.             Description = “Grocery Items”,
  34.           }
  35.       );
  36.     }
  37.  
  38.   }
  39. }

C#

Copy

Add a connection string in the appsettings.json file.

Microservice Using ASP.NET Core

Open the Startup.cs file to add the SQL server db provider for EF Core. Add the code services.AddDbContext<ProductContext>(o => o.UseSqlServer(Configuration.GetConnectionString(“ProductDB”))); under ConfigureServices method. Note that in the GetConnectionString method the name of the key of the connection string is passed that was added in appsettings file.

Adding Repository

Repository works as a micro component of microservice that encapsulates the data access layer and helps in data persistence and testability as well.

Add a new folder named Repository in the project and add an Interface name IProductRepository in that folder. Add the methods in the interface that performs CRUD operations for Product microservice.

Add a new concrete class named ProductRepository in the same Repository folder that implements IProductRepository. All these methods need:

  1. Add the implementation for the methods via accessing context methods.

    ProductRepository.cs
  2. using Microsoft.EntityFrameworkCore;
  3. using ProductMicroservice.DBContexts;
  4. using ProductMicroservice.Models;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8.  
  9. namespace ProductMicroservice.Repository
  10. {
  11.   public class ProductRepository: IProductRepository
  12.   {
  13.     private readonly ProductContext _dbContext;
  14.  
  15.     public ProductRepository(ProductContext dbContext)
  16.     {
  17.       _dbContext = dbContext;
  18.     }
  19.     public void DeleteProduct(int productId)
  20.     {
  21.       var product = _dbContext.Products.Find(productId);
  22.       _dbContext.Products.Remove(product);
  23.       Save();
  24.     }
  25.  
  26.     public Product GetProductByID(int productId)
  27.     {
  28.       return _dbContext.Products.Find(productId);
  29.     }
  30.  
  31.     public IEnumerable<Product> GetProducts()
  32.     {
  33.       return _dbContext.Products.ToList();
  34.     }
  35.  
  36.     public void InsertProduct(Product product)
  37.     {
  38.       _dbContext.Add(product);
  39.       Save();    }
  40.  
  41.     public void Save()
  42.     {
  43.       _dbContext.SaveChanges();
  44.     }
  45.  
  46.     public void UpdateProduct(Product product)
  47.     {
  48.       _dbContext.Entry(product).State = EntityState.Modified;
  49.       Save();
  50.     }
  51.   }

}

C#

Open the Startup class in the project and add the code as services.AddTransient<IProductRepository, ProductRepository>(); inside ConfigureServices method so that the repository’s dependency is resolved at a run time when needed.

Adding Controller

The microservice should have an endpoint for which a controller is needed which exposes the HTTP methods to the client as endpoints of the service methods.

Right click on the Controllers folder and add a new Controller as shown below.

Select the option “API Controller with read/write actions” to add the controller.

Give the name of the controller as ProductController.

A ProductController class will be added in the Controllers folder with default read/write actions that will be replaced later with product read/write actions and HTTP methods are created acting as an endpoint of the service.

ValuesController can be deleted as it is not needed.

Add implementation to the methods by calling the repository methods as shown below. The basic implementation is shown here for the sake of understanding the concept. The methods could be attribute routed and could be decorated with more annotations as per need.


  1. ProductController.cs
  2. using Microsoft.AspNetCore.Mvc;
  3. using ProductMicroservice.Models;
  4. using ProductMicroservice.Repository;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Transactions;
  8.  
  9. namespace ProductMicroservice.Controllers
  10. {
  11.   [Route(“api/[controller]”)]
  12.   [ApiController]
  13.   public class ProductController : ControllerBase
  14.   {
  15.  
  16.     private readonly IProductRepository _productRepository;
  17.  
  18.     public ProductController(IProductRepository productRepository)
  19.     {
  20.       _productRepository = productRepository;
  21.     }
  22.  
  23.     [HttpGet]
  24.     public IActionResult Get()
  25.     {
  26.       var products = _productRepository.GetProducts();
  27.       return new OkObjectResult(products);
  28.     }
  29.  
  30.     [HttpGet(“{id}”, Name = “Get”)]
  31.     public IActionResult Get(int id)
  32.     {
  33.       var product = _productRepository.GetProductByID(id);
  34.       return new OkObjectResult(product);
  35.     }
  36.  
  37.     [HttpPost]
  38.     public IActionResult Post([FromBody] Product product)
  39.     {
  40.       using (var scope = new TransactionScope())
  41.       {
  42.         _productRepository.InsertProduct(product);
  43.         scope.Complete();
  44.         return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
  45.       }
  46.     }
  47.  
  48.     [HttpPut]
  49.     public IActionResult Put([FromBody] Product product)
  50.     {
  51.       if (product != null)
  52.       {
  53.         using (var scope = new TransactionScope())
  54.         {
  55.           _productRepository.UpdateProduct(product);
  56.           scope.Complete();
  57.           return new OkResult();
  58.         }
  59.       }
  60.       return new NoContentResult();
  61.     }
  62.  
  63.     [HttpDelete(“{id}”)]
  64.     public IActionResult Delete(int id)
  65.     {
  66.       _productRepository.DeleteProduct(id);
  67.       return new OkResult();
  68.     }
  69.   }

}

C#

Copy

Entity Framework Core Migrations

Migrations allow us to provide code to change the database from one version to another.

Open Package Manager Console.

To enable the migration, type the command, Add-Migration and give that a meaningful name for e.g. InitialCreate and press enter.

Once the command is executed, if we look at our solution now, we see there’s a new Migrations folder. And it contains two files. One, a snapshot of our current context model. Feel free to check the files. The files are very much self-explanatory.

To ensure that migrations are applied to the database there’s another command for that. It’s called the update-database If executed, the migrations will be applied to the current database.

Check the SQL Server Management Studio to verify if the database got created.

When data of the Categories table is viewed the default master data of three categories is shown.

ValuesController can be deleted as it is not needed.

Run the Product Microservice

The service could be run via IIS Express i.e. Visual Studio default or via Docker container as well.

Via IIS Express

Choose IIS Express in the Visual Studio as shown below and press F5 or click that IIS Express button itself.

The application will be up once the browser page is launched. Since it has nothing to show, it will be blank, but the service could be tested via any API testing client. Here Postman is used to testing the service endpoints. Keep it opened and application running.

Install Postman if it is not on the machine and launch it.

POST

To test the POST method; i.e. create a new resource, select the method as POST in postman and provide the endpoint, i.e. https://localhost:44312/api/product and in the Body section, add a JSON similar to having properties of Product model as shown below and click on Send.

The response is returned with the Id of the product as well.

The “Post” method of the controller is responsible to create a resource in the database and send the response.

The line return CreatedAtAction(nameof(Get), new { id=product.Id }, product); returns the location of the created resource that could be checked in Location attribute in the response under Headers tab.

Perform a select query on the product table and an added row is shown for the newly created product.

Create one more product in a similar way.

GET

Perform a GET request now with the same address and two records are shown as a JSON result response.

DELETE

Perform the delete request by selecting DELETE as the verb and appending id as 1 (if the product with id 1 needs to be deleted) and press Send.

In the database, one record with Id 1 gets deleted.

PUT

PUT verb is responsible for updating the resource. Select PUT verb, provide the API address and in the Body section, provide details of which product needs to be updated in JSON format. For example, update the product with Id 2 and update its name, description, and price from Samsung to iPhone specific. Press Send.

Check the database to see the updated product.

Via Docker Containers

Running the service could be done via docker commands to be run in docker command prompt and using visual studio as well. Since we added the docker support, it is easy to run the service in docker container using visual studio.

Add container orchestrator support in the solution as shown below.

This will ask for the orchestrator. Select Docker Compose and press OK.

Once added to the solution, the solution will look like shown below having docker-compose with dockerignore and docker-compose.yml and its override file.

  1. As soon as the solution is saved, it builds the project under the container and creates a docker image. All the commands execution can be seen in the output window when the solution is saved.

Open the command prompt in admin mode and navigate to the same folder where the project files are.

Run the command docker images to see all the created images. We see the ProductMicroserviceimage the latest one.

Now run the application with Docker as an option as shown below.

Now, run the command docker ps to see the running containers. It shows the container is running on 32773:80 port.

Since the container is in running state, it is good to test the service now running under the container. To test the service, replace ”values” with “product” in the address as shown below. Ideally, it should get the product details. But it gives exception as shown below.

Running the same thing under IIS Express works fine i.e. on port 44312. Replace “values” with the product to get the product details,

  1. Since in IIS Express application runs fine and not in docker container, the error clearly shows that something is wrong with the SQL server that it does not understand our docker container or it is not running under docker container. In this scenario, the docker container is running as a separate machine inside the host computer. So, to connect to the SQL database in the host machine, remote connections to SQL needs to be enabled. We can fix this.
     

Open the SQL Server Configuration Manager. Now select Protocols for MSSQLSERVER and get the IPAll port number under TCP/IP section.

The connection string mentioned in the JSON file points to the data source as local which the docker container does not understand. It needs proper IP addresses with port and SQL authentication. So, provide the relevant details i.e. Data Source as Ip address, port number and SQL authentication details as shown below.

Now again run the application with Docker as an option like done earlier.

  1. This time the response is received.

Test the same in the Postman.

Test again with IIS Express URL.

Conclusion

A microservice is a service built around a specific business capability, which can be independently deployed which is called bounded context. This article on microservices focused on what microservices are and their advantages over monolithic services architecture. The article in detail described to develop a microservice using ASP.NET Core and run it via IIS and Docker container. Likewise, the service can have multiple images and could be run on multiple containers at the same point in time.

Leave a Comment

Your email address will not be published. Required fields are marked *

https://www.cooljerseyedge.com, https://www.collegeshopfan.com, https://www.kcchiefsgearusa.com, https://www.dlionsgearusa.com, https://www.bravensgearusa.com, https://www.cbengalsgearusa.com, https://www.gbpackersgearusa.com, https://www.htexansgearusa.com, https://www.laramsgearusa.com, Josh Allen Wyoming Jersey, https://www.dcowboysgearusa.com, https://www.mdolphinsgearusa.com, https://www.aliexfanshop.com, https://www.bestplayershop.com, https://www.collegeedgeshop.com, https://www.giantsonlinefans.com