Create Data-Driven Microservices with ASP.NET 5 with API Gateway

Create Data-Driven Microservices with ASP.NET 5 with API Gateway

Follow Me Here

Introduction

In this post, I am going to show you how to create a data-driven microservice with ASP.NET 5 with Ocelot API Gateway. I shall create a blank solution in Visual Studio 2019 Community edition to which I shall add the necessary projects. These are the Product, Customer and an API Gateway microservices created with ASP.NET 5 web api project template. In the latter posts we shall gradually build the microservices one by one adding the required CRUD functionalities.

Architectural Overview

In this post, I am going to show you how to create a data-driven microservice with ASP.NET 5 with Ocelot API Gateway Lets see Fig 1 below

Fig 1 shows an application consisting of two microservices: Customer and a Product microservice

The client app requests the various microservices through an API Gateway, which is also a microservice

This gateway re-routes all the api endpoints and unifies them under a single domain so if Customer microservices is deployed on port 4678 and Product on port 4789;

Customer at port 4678 , localhost:4678 will be rerouted as: localhost:4001/api/customer

Product at port 4789, localhost:4789 will be rerouted as localhost:4001/api/product (4001 being the API Gateway port)

Also note that each of the two microservices have their own databases and they are deployable as individual entities. These two are the characteristics of microservices which are meant to be loosely coupled hence ideally they should have their individual databases. Each of the microservices are independent unit because of this loose coupling among themselves that make them suitable to be deployed individually while other microservices are still running. It reduces the downtime of the entire enterprise app that may be comprised of these independent microservices.

Create a Blank Solution

Open Up Visual Studio 2019 and Click on Create a New project

On Configure your new project window put the Solution Name “Microservices.Api” with a suitable location and click Create

A Solution with no projects get created. Create a folder named Microservices at the root level.

Add a Product Microservice Web API project to the solution

Create a new project in this folder using the ASP.NET Core Web Application template and click Next

Give the Project the name Product.Microservice in Configure your new project window and Create:

On Create a new ASP.NET Core web application, highlight ASP.NET Core Web API with other defaults as shown below and click Create

Now the following screenshot shows our Solution Explorer with the newly created Product. Microservice project structure. We can see that it has a Properties and a Controllers folder. Properties folder has a file named launchsettings.json and the Controllers folder has a default WeatherForecastController.

The launchsettings.json file provides all the settings to launch the application:

There is also an appsettings.json file created at the root folder which will hold our database connection string as we shall see in a later lecture. By default it also creates a logging object with logging level information.

We also have two other important files in Program.cs and Startup.cs.

Program.cs

In a nutshell Program.cs has a Program Class that is the main entry point to the web application. At first, the web application initializes as a console application and uses the StartUp class and Host type to configure the web host with its associated services and middleware pipeline and run the application. The Program.cs has changed from the earlier 2.x version to version 3.0 through to 5.0 although at first glance it looks very similar to the former 2.x versions. This is because in .NET Core 3.0, ASP.NET Core has been rebuilt to run on top of the Generic Host

CreateHostBuilder method contains two separate method calls:

  • Host.CreateDefaultBuilder(). This configures the app configuration, logging, and dependency injection container.
  • IHostBuilder.ConfigureWebHostDefaults(). This adds everything else needed for a typical ASP.NET Core application, such as configuring Kestrel and using a Startup.cs to configure your DI container and middleware pipeline.

Startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Product.Microservice", Version = "v1" });
            });
            
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Product.Microservice v1"));
            }
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

IConfiguration is injected in the constructor in this template. In any real application you’ll almost certainly need access to this to configure your services, so it makes sense. ConfigureServices method is available to add any extension methods to the services collection. The AddControllers()  extension method adds the services required to use Web API Controllers. So you get Authorization, Validation, formatters for example. Since at the time of the project creation, I have included Enable Open API support, which means Swagger is automatically added to the ConfigureServices method and added to the IService collection instance. Swagger is then configured in the middleware pipeline within the Configure method to use SwaggerUI with its endpoints, in a development environment.

Create a Customer Microservice Web API in the solution

Now following all the steps as previously shown for the Product Microservice, create a Customer.Microservice Web API project using ASP.NET Core Web API template within the Microservices folder as shown below.

I will skip the explanation for the entire process as it is similar to the Product Microservice with all the explanations including those for the project structure and the important files valid in this case as well.

Create a Gateway.WebApi project

Now is the time to create the Gateway Api project. So in Visual Studio 2019, we configure our new project and name it Gateway.WebApi. This project is created on the root solution level (and not within the Microservices folder as this Gateway WebAPi project is shared by all the other microservices and therefore a level up in the project structure.) For this project, we choose the ASP.NET Core Empty template as this project will not contain any appreciable amount of coding.

On clicking the Create button above, the project is created and the Solution Explorer shows the following project structure.

The completed Microservices will be discussed in my forthcoming posts. So stay tuned !!

Follow Me Here

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.