Tutorials Microservices with .NET
Clean Architecture in ASP.NET Core Web API — Complete Guide
Clean Architecture in ASP.NET Core Web API — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Microservices with .NET on Toolliyo Academy.
On this page
Microservices with .NET · Lesson 5 of 131
Clean Architecture in ASP.NET Core Web API
Beginner → Intermediate → Advanced → Professional
Beginner · 1 — Foundations · ~6 min · Module 1: Foundations and Fundamentals
What is this?
Clean Architecture layers your code: Domain (business rules) in the center, Application (use cases), Infrastructure (database, HTTP clients) on the outside. Dependencies point inward — domain never references SQL.
Why should you care?
Microservices still need tidy code inside each service. Clean Architecture keeps Order rules testable without spinning up a database.
See it live — copy this example
Create a Web API project (dotnet new webapi), paste the code, then run dotnet run.
// Domain — no EF, no HTTP
public record OrderLine(int ProductId, int Qty, decimal UnitPrice);
public class Order
{
public Guid Id { get; } = Guid.NewGuid();
public decimal Total => _lines.Sum(l => l.Qty * l.UnitPrice);
private readonly List<OrderLine> _lines = new();
public void AddLine(OrderLine line) => _lines.Add(line);
}
// Application — use case
public class PlaceOrderHandler
{
public async Task<Guid> Handle(PlaceOrderCommand cmd, IOrderRepository repo)
{
var order = new Order();
foreach (var l in cmd.Lines) order.AddLine(l);
await repo.SaveAsync(order);
return order.Id;
}
}
Run Example »
Edit the code and click Run — like W3Schools Try it Yourself.
What happened?
- Order class knows business math.
- PlaceOrderHandler orchestrates.
- Repository interface lives in Application; SQL implementation lives in Infrastructure later.
Try it yourself
- Inside Order.Api, create folders Domain and Application.
- Add Order and OrderLine classes with no EF attributes.
- Add PlaceOrderHandler with IOrderRepository interface.
- Change a string or route in the example and save — watch Swagger or the RabbitMQ Management UI update.
- Break the code on purpose (remove a semicolon), read the error message, then fix it.
Remember
Domain = business rules; Infrastructure = details. Depend inward — domain has zero references to EF or ASP.NET. Handlers orchestrate one use case each.
Real-world: ShopNest Order service layers
When RBI audit asks "how is order total calculated?", you open Order.cs — not a 400-line controller.
Outcome: New developers find business rules in minutes, not by grep-ing controllers.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!