.NET Core Microservice Architecture implementation step by step

In this article, we will see about .NET Core Microservice Architecture and we will also see the implementation of Microservice Architecture with Ocelot API Gateway.

What is Microservice Architecture?

Microservice is a technique to build small services and each running and handling the logic independently. These are independent services which have their own database.

Microservice is basically a design pattern to break down a large and complex application into smaller and independent running module.

Benefits of using Microservice Architecture in Dot Net Core?

Using Microservice Architecture will give you below benefits.

  • Microservice Architecture makes development and deployment process easier.
  • Easy Testability
  • Easier to choose technology stack for each of the Microservice.

.NET Core Microservice Architecture implementation with Ocelot API Gateway

To understand Microservice Architecture I will implement this by using Ocelot API Gateway. Let’s dive into the details and start with understanding Ocelot?

What is Ocelot?

Ocelot is a .NET based API gateway which is used to build and implement .NET Core Microservice Architecture.

Ocelot offers below features –

  • Routing
  • Authentication
  • Authorization
  • Load Balancing
  • Caching
  • Request Aggregation

What is API Gateway?

An API Gateway is process that exists in-front of an API (Application Programming Interface) and is the single-entry point for client.

So API gateway avoid exposing multiple endpoints to client and instead it helps to expose one endpoint to consume.

Microservice Implementation with C# and .NET 5

Let’s implement Microservice Architecture with .NET 5 in Visual Studio 2019.

To do this, please follow below steps.

  1. Create 2 or more API Project in Visual Studio 2019
  2. Check if all your API is up and running.
  3. Next, create an Empty Web Project. This will be the Ocelot API Gateway project.
  4. Install Ocelot NuGet package, to do this, right click on Project and select Manage NuGet packages.
  5. Now search for Ocelot and install the first option from the search result as shown in below image.

6. Next, add the service in ConfigureService() method in Startup.cs file.

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddOcelot();//Ocelot Service
            services.AddRazorPages();
        }

7. Add Ocelot Middleware in Configure() method of Startup.cs file.

app.UseOcelot().Wait();

8. Create a JSON file and name it OcelotGateway.json. This file contains an array of Routes and a GlobalConfiguration.

{
    "Routes": [],
    "GlobalConfiguration": {}
}

Routes is the array to define DownStreamTemplate and UpStreamTemplate.

  • UpstreamPathTemplate – It tells about where to receive the requests.
  • DownstreamPathTemplate – It defines that where the incoming request should be forwarded.

To see the Ocelot Configuration details, please click here.

Below is the full content that I have used to implement.

Let’s understand below JSON file and related Keys as these are important aspects.

44303 is the Port used to host Weather Service in our case it will be Microservice 1.

44364 is the port used to host Value Service and this will be Microservice 2.

BaseUrl is the URL that hosts Ocelot API Gateway.

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/WeatherForecast",
      "DownStreamScheme": "https",
      "DownStreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": "44303"

        }
      ],
      "UpstreamPathTemplate": "/api/getweatherdetails",
      "UpstreamHttpMethod": [ "Get" ]
    },

    {
      "DownstreamPathTemplate": "/api/values",
      "DownStreamScheme": "https",
      "DownStreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": "44364"

        }
      ],
      "UpstreamPathTemplate": "/api/values",
      "UpstreamHttpMethod": [ "Get" ]
    }

  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://localhost:2001"
  }
}

So, as per above JSON configuration, client hits the URL https://localhost:2001/api/getWeatherdetails (Base URL and UpstreamPathTemplate) and it forward the request to https://localhost:44303/WeatherForecast (DownStreamHostsAndPorts and DownstreamPathTemplate)

9. You may see the application URL of Ocelot API Gateway Project which is defined in launchSettings.json file.

    "OcelotAPIGatewayDemo": {
      "commandName": "Project",
      "dotnetRunMessages": "true",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:2001;http://localhost:2002",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }

10. In Program.cs file you need to add OcelotGateway.json file in CreateHostBuilder() method as shown below.

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    webBuilder.ConfigureAppConfiguration(config => config.AddJsonFile($"OcelotGateway.json"));
                })
            .ConfigureLogging(logging=>logging.AddConsole());
    }

Run your Ocelot API Gateway project and hit the request and you will see the desired output.

Note: If you have create all the project in one solution then right click on Solution Name in Visual Studio 2019 and select “Set Startup Projects” and there you can set Multiple startup projects.

Hope you like this Article. In case you face any issue, write the same in comment box.

Please share this article among your tech group and please do like our Facebook page to join us and get latest updates.

You may subscribe to the YouTube channel for latest videos on .NET Core Technologies.

You may read this article – ASP.Net Core interview Questions and Answers

Please follow and like us:

Leave a Comment