IConfiguration vs IOptions NET
Synchronous and Asynchronous in .NET Core
Model Binding and Validation in ASP.NET Core
ControllerBase vs Controller in ASP.NET Core
ConfigureServices and Configure methods
IHostedService interface in .NET Core
ASP.NET Core request processing
| Asynchronous-Messaging | Bulkhead Pattern in .NET Core | |
Communication Between Microservices |
Communication between microservices in .NET Core can be achieved using several mechanisms, each suited to different scenarios. Here's a breakdown of the most common approaches, along with examples to help you get started:
In a microservices architecture, services are separate, self-contained processes that need to communicate to complete business tasks. The choice of communication pattern is critical, as it affects the system's resilience, performance, and scalability.
The main communication styles are:
Microservices expose endpoints using ASP.NET Core Web API.
Services communicate via HTTP using HttpClient.
// ProductServiceController.cs
[ApiController]
[Route("api/products")]
public class ProductServiceController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetProduct(int id)
{
var product = new Product { Id = id, Name = "Laptop" };
return Ok(product);
}
}
// InvoiceService.cs
public class InvoiceService
{
private readonly HttpClient _httpClient;
public InvoiceService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<Product> GetProductDetails(int productId)
{
var response = await _httpClient.GetAsync($"http://productservice/api/products/{productId}");
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<Product>();
}
}
📌 Use HttpClientFactory for better performance and resilience.
Services communicate via messages using brokers like RabbitMQ, Azure Service Bus, or Kafka.
Decouples services and improves scalability.
// Publisher (OrderService)
var factory = new ConnectionFactory() { HostName = "localhost" };
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.QueueDeclare(queue: "orderQueue", durable: false, exclusive: false, autoDelete: false);
string message = JsonSerializer.Serialize(order);
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "", routingKey: "orderQueue", body: body);
// Consumer (InventoryService)
channel.BasicConsume(queue: "orderQueue", autoAck: true, consumer: new EventingBasicConsumer(channel)
{
Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
var order = JsonSerializer.Deserialize<Order>(message);
// Process order
}
});
gRPC is a modern, high-performance RPC framework developed by Google that uses HTTP/2 for transport and Protocol Buffers (Protobuf) for message serialization. Its binary format and efficient protocol make it an ideal choice for low-latency, internal microservice communication.
Is Great for internal service communication.
// product.proto
service ProductService {
rpc GetProduct (ProductRequest) returns (ProductResponse);
}
Use Grpc.AspNetCore and Grpc.Net.Client packages in .NET Core.
Use Ocelot to route requests to appropriate microservices.
Handles authentication, logging, rate limiting .
{
"Routes": [
{
"DownstreamPathTemplate": "/api/products/{id}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [{ "Host": "localhost", "Port": 5001 }],
"UpstreamPathTemplate": "/products/{id}",
"UpstreamHttpMethod": [ "GET" ]
}
]
}
| Asynchronous-Messaging | Bulkhead Pattern in .NET Core | |