Tutorial · Hexagonal Architecture · Clean Architecture
Pierogi in the Hexagon
Hexagonal architecture in .NET explained over a beer — so that even your aunt gets it at a family party
Warm-up: what is this all about
Hexagonal architecture is a way of arranging code in which the heart of the application, the business logic, has no idea about the database, the framework, emails, text messages and the whole external circus. That's it. The rest of the course just unpacks this one sentence using pierogi.
The scene goes like this: Friday, 7:30 p.m., a pub, second beer. A friend sighs: "Listen, on the new project they want me to do some hexagon. Ports, adapters... I feel like I'm back in primary school geometry." So I grab a napkin and a pen and start drawing.
Who this is for
- For the junior who heard "hexagonal" in a job interview and nodded wisely.
- For the mid who does it on a project but feels it's just "more folders".
- For the senior who gets the topic but can't explain it to newcomers on the team.
- For the PM who finally wants to understand why "changing the SMS provider" took three sprints.
What you need to know
C# basics: a class, an interface, async/await. You don't need to know DDD, SOLID by heart or any patterns from thick books. The examples target .NET 10 and a real-life stack: ASP.NET Core with Swagger, MediatR, Mapster, EF Core with SQL Server, and Kafka. The code is in English, just like in real projects. Beer optional, but it helps.
The party plan
| Lesson | What it's about | Metaphor |
|---|---|---|
| 1. The problem | Why spaghetti code hurts | A flat with the fridge welded to the sofa |
| 2. The big idea | The heart of the application and the world around it | Halina's pierogi place |
| 3. Ports and adapters | Contract versus implementation | A socket and a travel adapter |
| 4. Glossary | The words people throw around in code review | A cheat sheet from the menu |
| 5. The golden rule | Dependencies point inwards | Halina doesn't know the wholesaler's number |
| 6. Solution structure | How to split it into .NET projects | The kitchen floor plan |
| 7. Code | From the domain to the controller and Program.cs | Making pierogi step by step |
| 8. Swapping an adapter | Adding Kafka without touching the logic | A new waitress |
| 9. Tests | Tests without a database and without Docker | A taste test before opening |
| 10. Deadly sins | Typical blunders | Halina in an apron with the wholesaler's logo |
| 11. When NOT to | Form over substance | Skyscraper foundations for a hot-dog stand |
| 12. Hex vs Onion vs Clean | How they differ | Same party, different T-shirts |
| 13. Hexagons and microservices | Three services, three controllers and Kafka between them | The pierogi place opens a chain |
At the end there's a fridge cheat sheet and a mini-quiz. Every lesson stands on its own, so you can read them separately, for example one a day on the tram.
The course also comes with the Pierogi place simulator with three interactive simulations: an order slip travelling through the hexagon with switchable adapters, three microservices talking over Kafka (with services you can switch off and consumer lag), and a clickable architecture test.
Lesson 1. The problem: a flat with the fridge welded to the sofa
Code without architecture works great until the first change. After that, every small fix means renovating the whole flat.
Imagine a flat where the fridge is welded to the sofa, the TV is bricked into the bathroom wall and the washing machine is plugged into the radiator. Everything works. Until you want to replace the fridge. Then you grab an angle grinder and cut through the sofa.
This is what a typical controller looks like in a project that "was supposed to be quick". A real example from life, just with pierogi:
[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
[HttpPost]
public async Task<IActionResult> Place(OrderRequest req)
{
// 1. A business rule crammed into the controller
if (req.Quantity > 100)
return BadRequest("More than 100 pieces? Weddings only!");
// 2. Hard-wired database (Dapper + connection string in code, a classic)
using var conn = new SqlConnection("Server=prod;Database=Pierogi;...");
await conn.ExecuteAsync("INSERT INTO Orders (Phone, Quantity) VALUES (@Phone, @Quantity)", req);
// 3. Hard-wired SMS, new HttpClient() right inside the method
var http = new HttpClient();
await http.PostAsJsonAsync("https://api.sms-provider.example/send",
new { to = req.Phone, text = "Halina is cooking!" });
return Ok();
}
}At first glance: 20 lines, it works, what more could you want. Now watch what happens when life knocks on the door.
Four scenes from life
- "Write a test for the 100-pierogi rule." To check a single
if, you have to spin up SQL Server and send a real text message. Preferably to yourself, at three in the morning, from CI. - "We're moving to Postgres." The SQL is scattered across 40 controllers. You search the whole repo for
SqlConnectionand pray nothing slips through. - "Text messages are too expensive, we're doing WhatsApp." Same story, just with
HttpClient. Someone copied the sending code into three places and each version is slightly different. - "Pyszne.pl will send us orders through a webhook." You copy the controller because it's faster. Now the "max 100 pieces" rule lives in two places. In six months someone will change it to 120 in only one of them.
Where the real problem lies
Not in someone using Dapper or HttpClient. The problem is that business rules and technical details are welded together. The most valuable part of the application, "how our pierogi place works", is swimming in a noodle soup of connection strings and URLs.
Hexagonal architecture simply means mounting all these appliances on plugs instead of welds. The fridge goes into a socket, the sofa stands on its own, and you replace each thing without an angle grinder.
Lesson 2. The big idea: Halina's pierogi place
All of hexagonal architecture fits into one small restaurant: the kitchen in the middle doesn't know where the order came from or who delivered the flour. And that's a very good thing.
Meet Mrs Halina. For 30 years she has been making pierogi in a small place in Oliwa, Gdańsk. Her rules are sacred: at least one pierogi per order, at most a hundred without advance notice, and every order must have a phone number so it's clear whom to call.
These rules are the domain. They are the entire value of this business. If the place closed tomorrow and reopened in another building, with other waitresses and another wholesaler, Halina's pierogi would taste exactly the same.
The left side: who wants something from the kitchen
Orders arrive by different routes, and each one speaks a different language:
- Jola the waitress shouts across the dining room: "Two ruskie, one with meat!"
- The phone: Mr Zdzisio mumbles something about "the cabbage ones, the usual".
- The Pyszne.pl app (a Polish food delivery platform) sends JSON with English field names.
But everything reaches the kitchen through a single hatch, always in the same format: an order slip saying "Ruskie x20, tel. 600 100 200". Halina doesn't read JSON and doesn't decode Zdzisio. That's the job of Jola, the phone operator and the tablet by the till.
The right side: what the kitchen needs from the world
The kitchen wants things from its surroundings, too:
- Record the order. Today in a notebook, tomorrow on a tablet, a year from now in the cloud.
- Let the customer know it's ready. A bell, a text message, WhatsApp, a shout through the window.
- Order flour. From the wholesaler, from the mill or from the discount store around the corner.
Halina only says: "I need 25 kg of flour in the back room by 7 a.m." Where the flour comes from and whose van brings it is no longer her concern.
Why a hexagon, of all shapes?
The name was coined by Alistair Cockburn, who described the idea around 2005. Its official, more boring name is Ports and Adapters. The six sides mean nothing. The point was a shape with many sides on which ports are easy to draw, and a break from drawing layers stacked one on top of another.
In short: it could have been an octagon, but then the diagram would look like a STOP sign and nobody would ever adopt it.
Remember this picture
- The middle is Halina's kitchen, that is, the business logic.
- The edges of the hexagon are the hatches and doors, that is, the ports.
- Outside stand Jola, the courier, the phone, the notebook and the wholesaler, that is, the adapters and all the technology.
Everything that follows is just an elaboration of this picture.
Lesson 3. Ports and adapters, or a USB-C socket and everything you plug into it
A port is the shape of the socket, an adapter is the plug. In code: a port is an interface, an adapter is a class that implements that interface.
Pick up a laptop. It has a USB-C socket on the side. You can plug a wall charger into that socket, a power bank, a docking station at the office or a cable from the car's cigarette lighter. The laptop hasn't the faintest idea where its power comes from. It only knows that something supplies it through USB-C.
Now the most important part: it was the laptop that decided what socket it has. The power bank manufacturer has to adapt, not the other way round. Nobody sensible rebuilds a laptop for a particular power bank.
And when you fly to London, where the wall sockets come from another planet? You don't solder anything inside the laptop. You buy a travel adapter at the airport for a few quid. The laptop won't even notice it's in England.
The same thing in C#
// PORT: "the socket in the laptop". It says WHAT is needed, not HOW.
public interface ICustomerNotifier
{
Task Notify(string phone, string message, CancellationToken ct);
}
// ADAPTER #1: "the wall charger", real text messages in production
public sealed class SmsCustomerNotifier(HttpClient http) : ICustomerNotifier
{
public async Task Notify(string phone, string message, CancellationToken ct)
{
var response = await http.PostAsJsonAsync("send", new { to = phone, text = message }, ct);
response.EnsureSuccessStatusCode();
}
}
// ADAPTER #2: "the power bank", for local development, costs nothing
public sealed class ConsoleCustomerNotifier : ICustomerNotifier
{
public Task Notify(string phone, string message, CancellationToken ct)
{
Console.WriteLine($"[HALINA SHOUTS THROUGH THE WINDOW at {phone}]: {message}");
return Task.CompletedTask;
}
}Code that needs to notify a customer gets an ICustomerNotifier in its constructor, and that's all. It doesn't know whether there's an SMS gateway on the other end or Console.WriteLine. Exactly like a laptop with a power bank.
The real-port test
A port names a business need, not a technology. A simple rule of thumb:
ICustomerNotifier,IOrderBook,IFlourSupplyare ports. They speak the language of the business: notify the customer, record the order, deliver the flour.ISmsSender,ISqlOrderRepository,IKafkaPublisherare adapters dressed up as ports. The technology sits right in the name.
If the interface name contains Sql, Sms, Http, Kafka or Redis, the socket has almost certainly been cut for one specific plug. Like a USB-C port that fits only one power bank from one company.
Lesson 4. A no-nonsense glossary
In code review you'll hear six words: domain, application, inbound port, outbound port, driving adapter and driven adapter. You already know all of them from the pierogi place.
| Word from a clever book | In plain words | In the pierogi place | In our code |
|---|---|---|---|
| Domain | Business rules that would be true even without a computer | Halina's recipe and rules | The Order class, the HalinaSaysNoException exception |
| Application, use case | The scenario "what happens when..." | "Someone places an order": accept it, record it, let people know | The MediatR handler PlaceOrderHandler |
| Inbound port (driving / primary port) | What the world can ask the application to do | The hatch for order slips | The command PlaceOrder : IRequest<OrderConfirmation> |
| Outbound port (driven / secondary port) | What the application needs from the world | The back door for suppliers | The interfaces IOrderBook, IOrderAnnouncer |
| Driving adapter (primary adapter) | Someone who calls the application and translates a foreign language into ours | Jola the waitress, the Pyszne.pl tablet | OrdersController (HTTP), a Kafka consumer |
| Driven adapter (secondary adapter) | Someone the application calls, who knows the technology | The wholesaler, the bell, the notebook | EfOrderBook (EF Core), KafkaOrderAnnouncer, the SMS gateway |
How not to mix up the left and right sides
Ask one question: who starts the conversation?
- If the world starts it (a customer clicks in Swagger, a message arrives from Kafka, a cron job fires), it's the left side. The adapter drives the application, hence the name "driving".
- If the application starts it ("save this", "send a text", "publish an event"), it's the right side. The application drives the adapter, so the adapter is "driven".
Careful: Kafka can stand on both sides at once. A consumer that reads orders from a topic is a driving adapter. A producer that publishes the "order placed" event is a driven adapter. Same technology, two different roles, like a waitress who takes orders in the morning and receives a delivery in the afternoon.
And where does MediatR fit?
MediatR is the postman inside the building. The adapter drops a slip (a command) into the mailbox, and MediatR carries it to the right cook (the handler). Command plus handler together form the inbound port and the use case. MediatR is not an architecture, just a convenient way of wiring one up.
Lesson 5. The golden rule: all arrows point inwards
The kitchen doesn't know anyone outside. It's the outsiders who know the kitchen and adapt to it. If you remember one thing from this course, let it be this.
Halina doesn't have the wholesaler's number in her phone. Instead, she pins a note on the back-room door: "Flour: 25 kg, paper sacks, delivery by 7:00." Whoever wants to supply her reads the note and adapts. Changing wholesalers? Halina doesn't even look up from her pastry board.
Normally the arrow points the wrong way
In spaghetti code, the business logic calls the database directly. That means the logic depends on EF Core and SQL Server. Change the database and you touch the logic.
In the hexagon we pull a dependency inversion trick (that's the "D" in SOLID):
- The kitchen (the
Applicationproject) defines theIOrderBookinterface itself. That's the note on the door. - The adapter (the
Adapters.SqlServerproject) implements this interface with theEfOrderBookclass, using EF Core. - So the dependency arrow goes from the adapter to the kitchen, not the other way round.
In practice you can check this in one second. Open Pierogarnia.Domain.csproj and there isn't a single PackageReference in it. Zero EF, zero Kafka, zero ASP.NET. The Application project only references Domain and the MediatR package.
So who introduces everyone to everyone?
The floor manager, that is, Program.cs. It's the only place in the entire application where everybody knows each other. The floor manager hires the waitress, signs the contract with the wholesaler and says: "Jola handles the hatch, we keep the notebook in SQL Server, and the bell is Kafka."
The technical name for this is the composition root. In .NET it's simply registration in the DI container, the builder.Services.Add... lines. The kitchen receives ready-made helpers in its constructor and doesn't ask where they came from.
Three check questions
- Is there any
using Microsoft.EntityFrameworkCorein theDomainproject? If so, Halina has a wholesaler's sales rep in her kitchen. - Is there a
using Confluent.KafkainApplication? If so, the kitchen calls the courier itself. - Does an endpoint or a Kafka consumer contain an
ifwith a business rule? If so, the waitress is making pierogi in the back room.
In lesson 9 I'll show you how to turn these questions into an automated test that fails the build when someone breaks the rule.
Lesson 6. Building the pierogi place in .NET 10: the solution structure
Five projects plus tests. Every NuGet package lives exactly where it belongs, and not one floor higher.
Pierogarnia/
├── src/
│ ├── Pierogarnia.Domain/ ← Halina's kitchen: entities and rules. ZERO packages.
│ ├── Pierogarnia.Application/ ← ports + use cases (MediatR)
│ ├── Pierogarnia.Adapters.SqlServer/ ← the pantry: EF Core + SQL Server
│ ├── Pierogarnia.Adapters.Kafka/ ← the bell and the door for Pyszne.pl: Confluent.Kafka + Mapster
│ └── Pierogarnia.Api/ ← HTTP window (controllers) + Swagger + the floor manager (Program.cs)
└── tests/
└── Pierogarnia.Tests/ ← the taste test, without opening the restaurantWho knows whom
| Project | Role in the hexagon | Project references | NuGet packages |
|---|---|---|---|
Domain | The middle, business rules | none | none |
Application | Ports and use cases | Domain | MediatR |
Adapters.SqlServer | Driven adapter (persistence) | Application | Microsoft.EntityFrameworkCore.SqlServer |
Adapters.Kafka | Driven adapter (publishing events) and driving adapter (the Pyszne.pl consumer) | Application | Confluent.Kafka, Mapster, Microsoft.Extensions.Hosting.Abstractions, Microsoft.Extensions.Options.ConfigurationExtensions |
Api | Driving adapter (HTTP) and composition root | all of the above | Microsoft.AspNetCore.OpenApi, Swashbuckle.AspNetCore.SwaggerUI, Mapster, Microsoft.EntityFrameworkCore.Design |
Tests | Tests of the kitchen and of the architecture | Application | xUnit (from the template), NetArchTest.Rules |
Notice one thing: the adapters don't know each other. Kafka doesn't know about SQL Server, and SQL Server doesn't know about Kafka. Each one only knows the kitchen. They're introduced to each other only by the floor manager in the Api project.
Setting it up from the terminal
mkdir Pierogarnia && cd Pierogarnia
dotnet new sln -n Pierogarnia
dotnet new classlib -n Pierogarnia.Domain -o src/Pierogarnia.Domain
dotnet new classlib -n Pierogarnia.Application -o src/Pierogarnia.Application
dotnet new classlib -n Pierogarnia.Adapters.SqlServer -o src/Pierogarnia.Adapters.SqlServer
dotnet new classlib -n Pierogarnia.Adapters.Kafka -o src/Pierogarnia.Adapters.Kafka
dotnet new web -n Pierogarnia.Api -o src/Pierogarnia.Api
dotnet new xunit -n Pierogarnia.Tests -o tests/Pierogarnia.Tests
dotnet sln add src/*/*.csproj tests/*/*.csproj
# Arrows point inwards
dotnet add src/Pierogarnia.Application reference src/Pierogarnia.Domain
dotnet add src/Pierogarnia.Adapters.SqlServer reference src/Pierogarnia.Application
dotnet add src/Pierogarnia.Adapters.Kafka reference src/Pierogarnia.Application
dotnet add src/Pierogarnia.Api reference src/Pierogarnia.Application src/Pierogarnia.Adapters.SqlServer src/Pierogarnia.Adapters.Kafka
dotnet add tests/Pierogarnia.Tests reference src/Pierogarnia.Application
# Packages only where they belong
dotnet add src/Pierogarnia.Application package MediatR
dotnet add src/Pierogarnia.Adapters.SqlServer package Microsoft.EntityFrameworkCore.SqlServer
dotnet add src/Pierogarnia.Adapters.Kafka package Confluent.Kafka
dotnet add src/Pierogarnia.Adapters.Kafka package Mapster
dotnet add src/Pierogarnia.Adapters.Kafka package Microsoft.Extensions.Hosting.Abstractions
dotnet add src/Pierogarnia.Adapters.Kafka package Microsoft.Extensions.Options.ConfigurationExtensions
dotnet add src/Pierogarnia.Api package Microsoft.AspNetCore.OpenApi
dotnet add src/Pierogarnia.Api package Swashbuckle.AspNetCore.SwaggerUI
dotnet add src/Pierogarnia.Api package Mapster
dotnet add src/Pierogarnia.Api package Microsoft.EntityFrameworkCore.Design
dotnet add tests/Pierogarnia.Tests package NetArchTest.RulesTwo things worth knowing before you start
Swagger in .NET 10 works a bit differently than it used to. Since .NET 9 the template no longer adds Swashbuckle, and the OpenAPI document is generated by the built-in Microsoft.AspNetCore.OpenApi package (Microsoft Learn). We add the Swagger UI itself separately, with the Swashbuckle.AspNetCore.SwaggerUI package, and point it at /openapi/v1.json.
MediatR has been dual-licensed since version 13. New versions are released under the RPL-1.5 licence or a commercial one. The free Community edition covers companies with less than USD 5 million in annual revenue, non-profits and education (Jimmy Bogard). In a large company, check the licence first. The alternative is a plain handler class injected through DI, and the hexagon works with it exactly the same way.
Lesson 7. Code step by step: we work from the inside out
We start with the kitchen and finish at the doors. First the rules, then the ports, then the use case, and only at the very end the database, Kafka, the controller and Swagger. That's the opposite of most tutorials, which start with dotnet ef migrations add. And that's the whole secret.
Step 1. The domain, or Halina's recipe
The file Pierogarnia.Domain/Order.cs. Notice that there isn't a single using for anything outside .NET.
namespace Pierogarnia.Domain;
public enum DumplingType { PotatoCheese, Meat, Cabbage, Blueberry }
public enum OrderStatus { Placed, Ready, Delivered }
public sealed class HalinaSaysNoException(string message) : Exception(message);
public sealed record OrderLine(DumplingType Type, int Quantity)
{
public decimal UnitPrice => Type switch
{
DumplingType.PotatoCheese => 2.50m,
DumplingType.Cabbage => 2.50m,
DumplingType.Meat => 3.00m,
DumplingType.Blueberry => 3.50m,
_ => throw new HalinaSaysNoException("Halina doesn't make that kind of pierogi.")
};
public decimal Value => UnitPrice * Quantity;
}
public sealed class Order
{
public const int MaxWithoutNotice = 100;
private readonly List<OrderLine> _lines = [];
public Guid Id { get; private set; }
public string Phone { get; private set; } = default!;
public OrderStatus Status { get; private set; }
public IReadOnlyList<OrderLine> Lines => _lines;
public int Pieces => _lines.Sum(l => l.Quantity);
public decimal Total => _lines.Sum(l => l.Value);
private Order() { } // for EF Core. Halina pretends she didn't see this.
public static Order Place(string phone, IEnumerable<OrderLine> lines)
{
if (string.IsNullOrWhiteSpace(phone))
throw new HalinaSaysNoException("No phone number? Who am I supposed to call?");
var order = new Order
{
Id = Guid.NewGuid(),
Phone = phone,
Status = OrderStatus.Placed
};
foreach (var line in lines)
order.Add(line);
if (order._lines.Count == 0)
throw new HalinaSaysNoException("An empty order slip? Halina doesn't cook air.");
return order;
}
private void Add(OrderLine line)
{
if (line.Quantity <= 0)
throw new HalinaSaysNoException("Zero pierogi is not an order, it's an insult.");
if (Pieces + line.Quantity > MaxWithoutNotice)
throw new HalinaSaysNoException("More than 100 pieces is wedding territory. Call a week ahead.");
_lines.Add(line);
}
}What matters here, one by one:
- You can't create a bad order. The constructor is private, and the only door is
Order.Place(...), which guards all the rules. Nobody will writenew Order { Phone = null }. - There are no public setters. The list of lines is read-only, so nobody can sneak in 500 pierogi through a side door.
- One exception for all of Halina's "no"s.
HalinaSaysNoExceptionis the language of the domain. The HTTP adapter will turn it into a 422, and the Kafka consumer into a log entry. - The only compromise is the empty constructor for EF Core. It's private and contains no logic. A purist will create a separate persistence model and map between them, a pragmatist will leave it as it is here. Both paths are fine.
Step 2. Ports, or notes on the doors
The file Pierogarnia.Application/Ports.cs. The hatch at the entrance and two notes on the back-room door.
using MediatR;
using Pierogarnia.Domain;
namespace Pierogarnia.Application;
// ===== INPUT PORT: the order slip you pass through the window =====
public sealed record PlaceOrder(string Phone, IReadOnlyList<OrderLineDto> Lines)
: IRequest<OrderConfirmation>;
public sealed record OrderLineDto(DumplingType Type, int Quantity);
public sealed record OrderConfirmation(Guid OrderId, int Pieces, decimal Total);
// ===== OUTPUT PORTS: notes pinned to the back door =====
public interface IOrderBook
{
Task Add(Order order, CancellationToken ct);
}
public interface IOrderAnnouncer
{
Task Announce(OrderPlaced orderPlaced, CancellationToken ct);
}
public sealed record OrderPlaced(
Guid OrderId, string Phone, IReadOnlyList<OrderLineDto> Lines, decimal Total, DateTimeOffset PlacedAt);The names speak the language of the business: IOrderBook is the order notebook, and IOrderAnnouncer is whoever announces the news. The words "SQL" and "Kafka" appear nowhere. The OrderPlaced event already carries the phone number and the lines, because in lesson 13 the kitchen and the couriers will need them.
And why is there no port for text messages here? Because the text message to the customer will be sent by a separate service that listens to events from Kafka (you'll see it in lesson 13). The kitchen only announces: "order placed". Who notifies the customer, and how, is none of its business.
Step 3. The use case, or Halina at work
The file Pierogarnia.Application/PlaceOrderHandler.cs. A MediatR handler is the scenario "what we do when an order slip comes in".
using MediatR;
using Pierogarnia.Domain;
namespace Pierogarnia.Application;
public sealed class PlaceOrderHandler(
IOrderBook orderBook,
IOrderAnnouncer announcer,
TimeProvider clock) : IRequestHandler<PlaceOrder, OrderConfirmation>
{
public async Task<OrderConfirmation> Handle(PlaceOrder command, CancellationToken ct)
{
// 1. Halina cooks (the domain guards every rule)
var order = Order.Place(
command.Phone,
command.Lines.Select(l => new OrderLine(l.Type, l.Quantity)));
// 2. Write it in the order book (the kitchen doesn't know it's SQL Server)
await orderBook.Add(order, ct);
// 3. Ring the bell (the kitchen doesn't know it's Kafka)
await announcer.Announce(
new OrderPlaced(order.Id, order.Phone, command.Lines, order.Total, clock.GetUtcNow()),
ct);
return new OrderConfirmation(order.Id, order.Pieces, order.Total);
}
}Read it out loud. It sounds like a description of Halina's work, not like code: make them, write it in the notebook, ring the bell. This is what a use case should look like: short, boring and business-focused.
Notice the TimeProvider, too. Even the clock is the outside world! If we wrote DateTimeOffset.UtcNow, a test checking the event date would be a lottery. TimeProvider has been built into .NET since version 8, so it's a port you don't even have to write.
Finally, registering the kitchen in DI, the file Pierogarnia.Application/KitchenRegistration.cs:
using Microsoft.Extensions.DependencyInjection;
namespace Pierogarnia.Application;
public static class KitchenRegistration
{
public static IServiceCollection AddKitchen(this IServiceCollection services, string? mediatRLicenseKey)
{
services.AddMediatR(cfg =>
{
cfg.LicenseKey = mediatRLicenseKey; // MediatR 13+: license key (Community edition has one too)
cfg.RegisterServicesFromAssembly(typeof(KitchenRegistration).Assembly);
});
return services;
}
}The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Step 4. The inbound adapter: an HTTP controller with Swagger and Mapster
- Step 5. The outbound adapter: a pantry on EF Core and SQL Server
- Step 6. The outbound adapter: a bell on Kafka
- Step 7. The floor manager, or Program.cs
- Fire it up and order
- Lesson 8. Adding Kafka: a new door to the kitchen without a renovation
- Step 1. Their language and our dictionary
- Step 2. The consumer, or the new waitress
- Step 3. Two lines in the registration
- The renovation bill
- Bonus: swapping an adapter on your local machine
- Lesson 9. Tests without opening the restaurant
- Fake adapters
- Use case tests
- A test that guards the architecture
- And the adapters?
- Lesson 10. The seven deadly sins of the hexagon (plus a bonus one)
- 1. Halina in an apron with the wholesaler's logo
- 2. A socket cut for a single plug
- 3. The waitress who makes pierogi in the back room
- 4. Halina who just signs off on someone else's work
- 5. Mapster shoves pierogi into the pot without Halina
- 6. MediatR as a GPS instead of a postman
- 7. An interface for every teaspoon
- 8. Bonus: writing to the database and to Kafka "on your word of honour"
- Lesson 11. When NOT to build a hexagon
- Hexagon light
- Lesson 12. Hex vs Onion vs Clean: same party, different T-shirts
- Where does Vertical Slice fit in all this?
- Lesson 13. Hexagons and microservices: the pierogi place opens a chain
- The rules of the game
- The solution structure
- Who publishes what, and who listens
- Step 1. Contracts, or the menu on the wall
- Step 2. Shared plumbing: one consumer for everyone
- Step 3. The Orders service and OrdersController
- Step 4. The Kitchen service and KitchenController
- Step 5. The Delivery service and DeliveriesController
- Step 6. Firing up the whole chain
- The flow of one order through three controllers
- What to watch out for when hexagons talk through Kafka
- Fridge cheat sheet and mini-quiz
- Mini-quiz