Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

Microservice Architecture in ASP.NET Core MVC

 

What is Microservice Architecture (Quick Practical Meaning)

Microservices architecture is an application architecture where a large application is divided into multiple small, independent services.

Each service:

  • Has one specific business responsibility
  • Can be developed independently
  • Can be deployed independently
  • Can scale independently
  • Usually owns its own database
  • Communicates with other services through APIs or messaging

Example: E-Commerce Application

Instead of creating one large application:

E-Commerce Application
        |
        +-- Users
        +-- Products
        +-- Orders
        +-- Payments
        +-- Inventory
        +-- Notifications

we create separate services:

                    API Gateway
                         |
       +-----------------+------------------+
       |                 |                  |
   User Service     Product Service     Order Service
       |                 |                  |
   User DB          Product DB          Order DB
                                           |
                                  +--------+--------+
                                  |                 |
                            Payment Service   Inventory Service
                                  |                 |
                              Payment DB       Inventory DB

Each service is independently deployable.


2. Monolith vs Microservices

Before understanding microservices, you should understand a monolithic application.

Monolithic Architecture

A traditional .NET application might look like:

                 ASP.NET Core Application
                         |
       +-----------------+-----------------+
       |                 |                 |
     Users            Products           Orders
       |                 |                 |
       +-----------------+-----------------+
                         |
                     SQL Server

Everything is inside one application.

For example:

MyECommerceApp
│
├── Controllers
│   ├── UsersController
│   ├── ProductsController
│   └── OrdersController
│
├── Services
├── Repositories
├── Models
└── Database

Advantages

  • Easy to start
  • Easy to debug
  • Simple deployment
  • Simple development
  • Easy local setup

Problems as application grows

Suppose your application becomes:

10 Developers
100 Developers
500 Developers

and contains:

User
Product
Order
Payment
Inventory
Shipping
Notification
Reporting
Analytics
AI

Eventually the application can become difficult to maintain.


3. Microservices Architecture

With microservices:

                     Client
                       |
                       v
                  API Gateway
                       |
       +---------------+---------------+
       |               |               |
       v               v               v
    Users           Products         Orders
    Service         Service          Service
       |               |               |
       v               v               v
    User DB        Product DB       Order DB

Additional services:

Orders
   |
   +----> Payment Service
   |
   +----> Inventory Service
   |
   +----> Notification Service

Each service has its own responsibility.


4. Advantages of Microservices

4.1 Independent Deployment

Suppose you change only Payment Service.

You don't necessarily need to redeploy:

User Service
Product Service
Order Service
Inventory Service

You deploy:

Payment Service

4.2 Independent Scaling

Suppose your application receives:

100,000 product requests/hour
10,000 order requests/hour
1,000 payment requests/hour

You might scale Product Service more heavily:

Product Service

Instance 1
Instance 2
Instance 3
Instance 4
Instance 5

while Payment Service might only need:

Payment Service

Instance 1
Instance 2

5. Technology Independence

Different services can theoretically use different technologies.

For example:

User Service
    ASP.NET Core

Product Service
    ASP.NET Core

Recommendation Service
    Python

Analytics Service
    Python

Search Service
    Elasticsearch

You don't have to use the same technology everywhere.

However, don't introduce different technologies just because you can. It increases operational complexity.


6. Fault Isolation

Suppose:

Recommendation Service

has a problem.

The rest of the application may still work:

Users       → Working
Products    → Working
Orders      → Working
Payments    → Working
Recommendation → Down

This is much better than having one failure bring down the entire application.


7. Team Independence

Different teams can own different services.

Team A → User Service
Team B → Product Service
Team C → Order Service
Team D → Payment Service
Team E → Notification Service

This becomes particularly valuable for large organizations.


8. Disadvantages of Microservices

Microservices aren't automatically better.

They introduce significant complexity.

Distributed system problems

You now have:

Service A
   |
Network
   |
Service B
   |
Network
   |
Service C

Networks can fail.

You must deal with:

  • Timeouts
  • Retries
  • Service discovery
  • Authentication
  • Authorization
  • Logging
  • Distributed tracing
  • Monitoring
  • Message queues
  • Data consistency
  • Deployment
  • Container orchestration

Therefore:

Don't use microservices simply because they are popular.

For a small application, a modular monolith may be a better architecture.


🧱 Step-by-Step Practical Implementation in .NET Core

We’ll build a simple system:

👉 Services:

  1. User Service
  2. Product Service
  3. Order Service
  4. API Gateway

🧩 Step 1: Create Multiple Web API Projects

In Visual Studio / CLI:

dotnet new webapi -n UserService
dotnet new webapi -n ProductService
dotnet new webapi -n OrderService

👉 Each project = One microservice


🧩 Step 2: Design Each Service Independently

✅ Example: UserService

Model

public class User
{
public int Id { get; set; }
public string Name { get; set; }
}

Controller

[ApiController]
[Route("api/users")]
public class UsersController : ControllerBase
{
private static List<User> users = new List<User>()
{
new User { Id = 1, Name = "Shiva" }
};

[HttpGet]
public IActionResult GetUsers()
{
return Ok(users);
}
}

✅ Example: ProductService

[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
return Ok(new[] { "Laptop", "Mobile" });
}
}

✅ Example: OrderService (Calling Other Services)

This is where microservices become real 👇

[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
private readonly HttpClient _httpClient;

public OrdersController(HttpClient httpClient)
{
_httpClient = httpClient;
}

[HttpGet]
public async Task<IActionResult> GetOrders()
{
var users = await _httpClient.GetStringAsync("https://localhost:5001/api/users");
var products = await _httpClient.GetStringAsync("https://localhost:5002/api/products");

return Ok(new
{
OrderId = 1,
User = users,
Product = products
});
}
}

🧩 Step 3: Register HttpClient (IMPORTANT)

In Program.cs of OrderService:

builder.Services.AddHttpClient();

🧩 Step 4: Run Services on Different Ports


1. Easiest: launchSettings.json

Open:

Properties/launchSettings.json

Find the applicationUrl setting:

{
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5001",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Then run:

Example:

ServicePort
UserService5001
ProductService5002
OrderService5003

🧩 Step 5: Add API Gateway (Ocelot)

👉 Create Gateway Project:

dotnet new webapi -n ApiGateway

👉 Install Ocelot:

dotnet add package Ocelot

Configure ocelot.json

{
"Routes": [
{
"DownstreamPathTemplate": "/api/users",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 5001 }
],
"UpstreamPathTemplate": "/users",
"UpstreamHttpMethod": [ "GET" ]
}
],
"GlobalConfiguration": {
"BaseUrl": "https://localhost:7000"
}
}

Update Program.cs

builder.Configuration.AddJsonFile("ocelot.json");

builder.Services.AddOcelot();

var app = builder.Build();

await app.UseOcelot();
app.Run();

👉 Now instead of calling:

https://localhost:5001/api/users

You call:

https://localhost:7000/users

Method 1: Using launchSettings.json (Most Common)

📁 Path:

Properties/launchSettings.json

Example:

{
"profiles": {
"UserService": {
"commandName": "Project",
"applicationUrl": "https://localhost:5001;http://localhost:5000"
}
}
}

👉 Change ports like this:

"applicationUrl": "https://localhost:6001;http://localhost:6000"

✅ Now your app runs on:


🔷 Method 2: From Program.cs (Code-Level Control)

Use Kestrel configuration:

var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel(options =>
{
options.ListenAnyIP(5001); // HTTP
options.ListenAnyIP(5002, listenOptions =>
{
listenOptions.UseHttps(); // HTTPS
});
});

var app = builder.Build();
app.Run();



Post a Comment

0 Comments