Building Microservices with .NET
Introduction
Microservices architecture is a style that structures an application as a collection of loosely coupled services, which implement business capabilities. This tutorial will guide you through building microservices with .NET, covering setup, development, and deployment.
Step 1: Setting up Your .NET Microservices Solution
Create a new solution and projects for your microservices. You can do this using the .NET CLI or Visual Studio.
// Using .NET CLI
dotnet new sln -n MicroservicesExample
dotnet new webapi -n ProductService
dotnet new webapi -n OrderService
dotnet sln add ProductService/ProductService.csproj
dotnet sln add OrderService/OrderService.csproj
Step 2: Configuring Each Microservice
Each microservice will have its own Startup.cs
and appsettings.json
. Configure the services and middleware required for each microservice.
// ProductService/Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
// OrderService/Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Step 3: Creating Models and DbContexts
Create the models and DbContext classes for each microservice to interact with the database.
// ProductService/Models/Product.cs
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
// ProductService/Data/ProductDbContext.cs
public class ProductDbContext : DbContext
{
public ProductDbContext(DbContextOptions options) : base(options) { }
public DbSet Products { get; set; }
}
// OrderService/Models/Order.cs
public class Order
{
public int Id { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
}
// OrderService/Data/OrderDbContext.cs
public class OrderDbContext : DbContext
{
public OrderDbContext(DbContextOptions options) : base(options) { }
public DbSet Orders { get; set; }
}
Step 4: Creating Controllers
Create the controllers for each microservice to handle API requests.
// ProductService/Controllers/ProductsController.cs
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly ProductDbContext _context;
public ProductsController(ProductDbContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult> GetProducts()
{
return Ok(await _context.Products.ToListAsync());
}
[HttpGet("{id}")]
public async Task<ActionResult> GetProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
[HttpPost]
public async Task<ActionResult> CreateProduct(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
}
// OrderService/Controllers/OrdersController.cs
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
private readonly OrderDbContext _context;
public OrdersController(OrderDbContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult> GetOrders()
{
return Ok(await _context.Orders.ToListAsync());
}
[HttpGet("{id}")]
public async Task<ActionResult> GetOrder(int id)
{
var order = await _context.Orders.FindAsync(id);
if (order == null)
{
return NotFound();
}
return Ok(order);
}
[HttpPost]
public async Task<ActionResult> CreateOrder(Order order)
{
_context.Orders.Add(order);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetOrder), new { id = order.Id }, order);
}
}
Step 5: Running and Testing Your Microservices
Run your microservices using the .NET CLI or Visual Studio. Test the endpoints using tools like Postman or Swagger to ensure that they are working correctly.
Conclusion
In this tutorial, we covered the basics of setting up and building microservices with .NET. We created a solution with multiple microservice projects, configured services and middleware, created models and DbContexts, and implemented controllers. This should give you a strong foundation to build upon for developing complex microservice architectures with .NET.