Part 4 of 12 in Clean Architecture in .NET
Setting Up the Infrastructure Layer in Clean Architecture: EF Core, Dapper and Domain Events
· 16 min read
The infrastructure layer connects the application to the outside world. This article sets it up in .NET with EF Core, migrations, domain event dispatch, Dapper and PostgreSQL in Docker. It is Part 4 of the Clean Architecture in .NET series.
In Part 3, the Application layer declared what it needs from the outside: IApplicationDbContext and IEmailService, and its handlers take .NET’s TimeProvider. This part writes the implementations in Ecommerce.Infrastructure, and runs the database they talk to.
Infrastructure references Application and Domain. It is the only project that knows about PostgreSQL and Dapper, and the only one that configures EF Core. Application references EF Core too, for the DbSet<T> properties of IApplicationDbContext. At the end, the solution builds, the first migration exists, and PostgreSQL runs in Docker.
Packages
Infrastructure is where the database packages go. As in Part 1, each one is a PackageVersion under an Infrastructure label in Directory.Packages.props, and a PackageReference without a version in the project:
<ItemGroup>
<PackageReference Include="Dapper" />
<PackageReference Include="EFCore.NamingConventions" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" />
<PackageReference Include="Npgsql" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
</ItemGroup>
These are the database packages, plus Microsoft.Extensions.Configuration.Abstractions for the IConfiguration that AddInfrastructure reads the connection string from. The versions are in this part’s Directory.Packages.props.
The DbContext
ApplicationDbContext is the implementation of IApplicationDbContext:
public sealed class ApplicationDbContext(DbContextOptions options, IDomainEventsDispatcher domainEventsDispatcher)
: DbContext(options), IApplicationDbContext
{
public DbSet<Product> Products => Set<Product>();
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(ApplicationDbContext).Assembly);
base.OnModelCreating(modelBuilder);
}
}
The real class has one DbSet for each aggregate root: categories, coupons, products, orders, reviews and users. OrderItem has none, because it is loaded through its Order.
ApplyConfigurationsFromAssembly finds every IEntityTypeConfiguration<T> in the project. So a new entity needs a new configuration class, and nothing else changes in the context.
Entity configurations
Why configurations and not attributes on the entities? Because attributes such as [MaxLength] come from EF Core packages, and Domain references no packages (Part 1). The entity stays plain C#.
Each entity has one configuration class, and all of them are in this part’s code. The migration needs all of them. This is part of ProductConfiguration:
internal sealed class ProductConfiguration : IEntityTypeConfiguration<Product>
{
public void Configure(EntityTypeBuilder<Product> builder)
{
builder.ToTable("products");
builder.HasKey(product => product.Id);
builder.Property(product => product.Id)
.HasConversion(productId => productId.Value, value => new ProductId(value));
builder.Property(product => product.Name)
.HasMaxLength(ProductName.MaxLength)
.HasConversion(name => name.Value, value => ProductName.Create(value).Value);
builder.OwnsOne(product => product.Price, priceBuilder =>
{
priceBuilder.Property(money => money.Amount)
.HasColumnType("decimal(18, 2)");
priceBuilder.Property(money => money.Currency)
.HasConversion(currency => currency.Code, code => Currency.FromCode(code).Value)
.HasDefaultValue(Currency.Bdt);
});
// Restrict, not cascade: deleting a category must not delete its products.
builder.HasOne<Category>()
.WithMany()
.HasForeignKey(product => product.CategoryId)
.OnDelete(DeleteBehavior.Restrict);
}
}
Three patterns repeat in every configuration.
Strongly typed IDs. EF Core doesn’t know ProductId. HasConversion tells it to store the Guid inside and to rebuild the record when reading. Every key gets one. A foreign key such as Product.CategoryId needs none: EF Core uses the converter of the key it points to.
Single-value value objects. ProductName has a private constructor (Part 2), so the conversion back goes through its Create method. Create returns a Result, and .Value throws on a failure. That is on purpose: a name in the database that fails validation means the data is corrupt, and that is a bug, not an expected failure.
Money as an owned type. OwnsOne stores Money in the same table, as the columns price_amount and price_currency. It has no table and no ID of its own. The currency is a value object too, so it is stored as its code.
Foreign keys to other aggregates use HasOne<Category>().WithMany() with no navigation property, so Product holds a CategoryId and never a Category. Three of these foreign keys use DeleteBehavior.Restrict: deleting a category must not delete its products, deleting a product must not delete the lines of past orders, and deleting a coupon must not delete the orders that used it.
Snake_case names
PostgreSQL folds unquoted names to lowercase. A PriceAmount column would have to be quoted in every hand-written query, forever. So the DbContext is registered with UseSnakeCaseNamingConvention() from the EFCore.NamingConventions package, and columns become price_amount automatically. I set the table names explicitly with ToTable("products").
The same names matter later for Dapper, because its SQL is written against these tables.
CS8618 and the constructors EF Core uses
In Part 2, Entity<TId> has a protected parameterless constructor, and Order, OrderItem and Product have private ones, each with #pragma warning disable CS8618 around it. Here is why those three need it, and why the others don’t.
EF Core can call a constructor with parameters, even a private one, when each parameter matches a mapped property by name and type. It can’t set a navigation property through a constructor.
Look at Category. Its private constructor takes (CategoryId id, CategoryName name, CategoryCode code, DateTime createdOnUtc), and every parameter matches a property that has a value conversion. So EF Core calls it directly. Category has no parameterless constructor, and the compiler has nothing to warn about, because every non-nullable property is set in the constructor. User, Review and Coupon work the same way.
Now Product. Its constructor takes Money price, and Price is an owned type, which EF Core treats as a navigation. It can’t be bound through a constructor. So EF Core has no constructor it can use with Price, and the entity needs a parameterless one. The same goes for Order (TotalPrice) and OrderItem (UnitPrice, and its Product navigation). The constructor is empty, and EF Core sets the properties after it:
#pragma warning disable CS8618 // Used by EF Core to materialize the entity
private Product()
{
}
#pragma warning restore CS8618
CS8618 warns that a non-nullable property has no value when the constructor ends. Here that is true for a moment, until EF Core fills the properties. With warnings as errors (Part 1), the warning would fail the build, so the #pragma covers only that constructor, with the reason next to it. I don’t turn CS8618 off for the whole solution, because it still catches a forgotten property in every other constructor.
Could the entities avoid it? Only by changing the domain to fit EF Core, for example by making Money two plain properties on Product. I prefer one small, explained #pragma over a worse domain model.
So the rule is: add a parameterless constructor only when EF Core can’t bind one with parameters. Here that means an entity with an owned type. An entity whose constructor parameters all map to properties doesn’t need one, and an extra one is only one more way to create the entity without its rules.
Migrations
Migrations are generated from the configurations with dotnet ef, a .NET tool. It starts the API project to find the DbContext, so that project needs the Microsoft.EntityFrameworkCore.Tools package and a connection string. Put the string in Ecommerce.API/appsettings.Development.json:
{
"ConnectionStrings": {
"Database": "Host=database-postgres;Port=5432;Database=ecommercedb;Username=postgres;Password=postgres;"
}
}
Install the tool once with dotnet tool install --global dotnet-ef, then create the first migration:
dotnet ef migrations add Initial --project Ecommerce.Infrastructure --startup-project Ecommerce.API
The generated files go to Ecommerce.Infrastructure/Migrations.
With analyzers as errors, the first generated migration fails the build with rules such as IDE0053 and IDE0161. I don’t want to suppress those rules for the whole solution, and I can’t edit generated files. So the Migrations folder is marked as generated code at the top of .editorconfig:
# Ignore paths
[**/Migrations/**]
generated_code = true
Analyzers skip files marked as generated, so only the migrations are exempt.
Don’t edit a generated migration to change the model: change the configuration and generate a new one. A hand-written step that EF Core can’t generate, such as moving data, is the exception. And read the generated Up before committing. If it contains more than the change you intended, the model drifted.
Dispatching domain events after the save
In Part 2, an aggregate root collects its domain events in a private list. Something has to take them, and only after the data is saved. That is the DbContext, because it is the one place every save goes through:
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
int result = await base.SaveChangesAsync(cancellationToken);
await PublishDomainEventsAsync();
return result;
}
private async Task PublishDomainEventsAsync()
{
// Pulling empties each aggregate's list, so a second SaveChangesAsync can't publish the same event twice.
List<IDomainEvent> domainEvents =
[
.. ChangeTracker
.Entries<IHasDomainEvents>()
.SelectMany(entry => entry.Entity.PullDomainEvents()),
];
await domainEventsDispatcher.DispatchAsync(domainEvents);
}
The flow of one save:
- The handler calls
SaveChangesAsync. base.SaveChangesAsyncwrites the changes in a transaction.- The context pulls the events of every tracked aggregate that implements
IHasDomainEvents. Pulling also empties each aggregate’s list. - It dispatches them.
Why after the save? Because an event says that something happened. If the save fails, nothing happened. With the dispatch before the save, an order that violates a database constraint would still send its confirmation email. Emptying the lists matters too: if the events stayed on the aggregates, a second SaveChangesAsync on the same context would publish them again.
The dispatcher
The DbContext only knows an interface, declared in Infrastructure next to its implementation:
public interface IDomainEventsDispatcher
{
Task DispatchAsync(IEnumerable<IDomainEvent> domainEvents, CancellationToken cancellationToken = default);
}
DomainEventsDispatcher finds the handlers for each event. The handlers are IDomainEventHandler<TEvent> classes in Application (Part 3).
The problem is that the dispatcher only knows each event as an IDomainEvent. Its real type is known at runtime, as a Type. But IDomainEventHandler<TEvent> is generic, and C# can’t call HandleAsync on it without knowing TEvent at compile time.
The domain solves that in the handler interface itself. Every typed handler is also an untyped one, and a default interface method does the cast:
public interface IDomainEventHandler
{
Task HandleAsync(IDomainEvent domainEvent, CancellationToken cancellationToken);
}
public interface IDomainEventHandler<in TEvent> : IDomainEventHandler
where TEvent : IDomainEvent
{
Task HandleAsync(TEvent domainEvent, CancellationToken cancellationToken);
// The dispatcher resolves handlers for the event's runtime type, so this cast always succeeds.
Task IDomainEventHandler.HandleAsync(IDomainEvent domainEvent, CancellationToken cancellationToken) =>
HandleAsync((TEvent)domainEvent, cancellationToken);
}
A handler in Application still implements only IDomainEventHandler<OrderPlacedDomainEvent> and writes only the typed method. It gets the untyped one for free. So the dispatcher can stay small. It creates a new DI scope for each event, resolves all handlers for that event type, and calls them one by one through the untyped interface:
internal sealed class DomainEventsDispatcher(IServiceScopeFactory scopeFactory) : IDomainEventsDispatcher
{
public async Task DispatchAsync(IEnumerable<IDomainEvent> domainEvents, CancellationToken cancellationToken = default)
{
foreach (IDomainEvent domainEvent in domainEvents)
{
// A new scope per event: its handlers get their own DbContext, not the one that just saved.
await using AsyncServiceScope scope = scopeFactory.CreateAsyncScope();
// Handlers are registered as IDomainEventHandler<TEvent> for the concrete event type.
Type handlerType = typeof(IDomainEventHandler<>).MakeGenericType(domainEvent.GetType());
// Every typed handler is also an untyped IDomainEventHandler, which does the cast itself.
foreach (IDomainEventHandler handler in scope.ServiceProvider.GetServices(handlerType).OfType<IDomainEventHandler>())
{
await handler.HandleAsync(domainEvent, cancellationToken);
}
}
}
}
MakeGenericType builds the handler type for the event’s runtime type, which is all the reflection there is. The cast itself lives in one line of the interface, so there is no wrapper class and no cache to maintain.
Why a new scope? Because a handler gets its own IApplicationDbContext and its own services, so it doesn’t share the tracked entities of the save that triggered it.
What this design costs
This is in-process dispatch. The handlers run synchronously inside the request, after the commit, with no outbox. That has consequences:
- The data is already saved when the handlers run. If a handler throws, the request fails (a 500), but the order exists, and the events are already pulled, so nothing retries them. A client that retries the request places a second order.
- Slow handlers make the request slow, because the response waits for them.
SaveChangesAsyncdoesn’t pass itscancellationTokento the dispatcher, so a cancelled request doesn’t stop the handlers. That is a gap I haven’t closed.- Only
SaveChangesAsyncdispatches. The synchronousSaveChanges()isn’t overridden, so a save through it raises no events. - The events are read from the entities the change tracker still has after the save. A deleted entity is detached by then, so an event it raised is lost.
I use in-process dispatch here for simplicity. It is enough while the handlers are a welcome email and an order confirmation. The three options, and when each fits:
- In-process dispatch (this code). Nothing to run or operate. The cost is the list above: the request waits for the handlers, and an event is lost if a handler fails.
- A
Channel<T>and a background service. The request writes the event to an in-memory channel and returns, and a hosted service runs the handlers. The request no longer waits for them. But the queue lives in memory, so a restart or a crash loses whatever is still in it. - An outbox. The events are saved as rows in the same transaction as the data, and a background job publishes them later and marks them done. An event is never lost, and a failed handler is retried. The cost is a table, a job, and handlers that must be safe to run twice.
I’d move to an outbox when an event must not be lost, for example when it charges a payment or tells another service about an order.
Dapper and NpgsqlDataSource
My rule for the split: EF Core for most reads and writes in the handlers, through IApplicationDbContext. A Dapper query behind a repository when the query joins several tables and returns selected columns, when the operation is an existing stored procedure, or when it is a complex operation that is easier and more efficient in raw SQL. Why not a repository for everything? Because the number of repository methods keeps growing with every new filter, and DbContext already works like a repository and a unit of work. Part 3 has the full reasoning.
Dapper needs an open connection. Npgsql already has the type for that, NpgsqlDataSource: it holds the connection string and the connection pool, and hands out open connections. It is registered once, as a singleton:
services.AddSingleton(_ => NpgsqlDataSource.Create(GetConnectionString()));
A repository takes the data source and opens a connection per query:
await using NpgsqlConnection connection = await dataSource.OpenConnectionAsync(cancellationToken);
Why not a small factory interface of my own? Because it would only wrap what the data source already does. NpgsqlDataSource is the type Npgsql recommends for this since version 7: one object per database, one pool, connections opened asynchronously and with the request’s cancellation token. Disposing the connection returns it to the pool.
The connection is a new one from the pool, not the DbContext’s, so a Dapper query doesn’t run in EF Core’s transaction and doesn’t see changes that aren’t saved yet.
The queries are written against the snake_case tables, and each column gets an alias that matches the response type, such as p.price_amount AS PriceAmount.
The same on SQL Server
On SQL Server with Microsoft.Data.SqlClient, I use the same idea: one singleton that holds the connection string and opens a connection for each query. SqlClient pools connections per connection string, so a new SqlConnection per query takes an existing one from the pool:
public sealed class SqlServerConnectionOpener(string connectionString)
{
public async Task<SqlConnection> OpenAsync(CancellationToken cancellationToken)
{
var connection = new SqlConnection(connectionString);
try
{
await connection.OpenAsync(cancellationToken);
return connection;
}
catch
{
// Opening failed, so the caller never gets the connection to dispose.
await connection.DisposeAsync();
throw;
}
}
}
It is registered the same way, read on first use:
services.AddSingleton(_ => new SqlServerConnectionOpener(GetConnectionString()));
And a repository opens its connection the same way:
await using SqlConnection connection = await connectionOpener.OpenAsync(cancellationToken);
Everything else in this part (the Dapper queries behind a repository, the separate connection from EF Core’s) stays the same. Only the SQL dialect changes: SQL Server quotes names with brackets and pages with OFFSET ... FETCH.
Implementing the ports
The clock needs no implementation of its own: Infrastructure registers .NET’s system clock, services.AddSingleton(TimeProvider.System), so a handler gets the real time and a test can pass a fixed one (Part 3). The email port has a small implementation:
public sealed class EmailService : IEmailService
{
public Task SendAsync(Email email, string subject, string body)
{
return Task.CompletedTask;
}
}
The email service is a stub that sends nothing. I haven’t connected a real provider, so the welcome and confirmation handlers run, but no email goes out. A real provider replaces this class and adds its settings. Nothing in Application changes, because it only knows IEmailService. The sender would also have to catch its own failures, because a handler that throws turns a saved order into a 500.
Registering the layer
AddInfrastructure is the one method Program.cs calls (Part 1). The persistence part:
private static void AddPersistence(IServiceCollection services, IConfiguration configuration)
{
string GetConnectionString() => configuration.GetConnectionString("Database")
?? throw new InvalidOperationException("Connection string 'ConnectionStrings:Database' is not configured.");
services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(GetConnectionString()).UseSnakeCaseNamingConvention());
services.AddScoped<IApplicationDbContext>(sp => sp.GetRequiredService<ApplicationDbContext>());
services.AddSingleton(_ => NpgsqlDataSource.Create(GetConnectionString()));
}
Both IApplicationDbContext and ApplicationDbContext resolve to the same scoped instance. In the same AddInfrastructure method, the clock is registered as a singleton (TimeProvider.System), and the email service and the dispatcher as transient services.
The connection string is read when the DbContext or the data source is first resolved, not when the services are registered. Why? Because tools such as build-time OpenAPI generation start the app without any environment configuration and never touch the database. Reading it at registration would make them throw.
The trade-off: in Production, a missing connection string fails on the first database call instead of at startup. In Development it still fails at startup, because the migrations run then.
PostgreSQL in Docker
The database runs in its own compose project, infra.compose.yml, and the API runs in another one. Why two files? So that when I stop and restart the API, the infrastructure containers keep running. It is also close to production, where the database doesn’t restart with the application.
name: ecommerce-infra
services:
database-postgres:
image: postgres:18.6
container_name: database-postgres
environment:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
- postgres-data:/var/lib/postgresql/18/docker
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"]
networks:
- ecommerce-network
volumes:
postgres-data:
networks:
ecommerce-network:
name: ecommerce-network
driver: bridge
The network has a fixed name, ecommerce-network, so the API’s compose project can join it and reach the database by its container name. The three POSTGRES_ values come from an .env.dev file next to it:
POSTGRES_DB=ecommercedb
POSTGRES_USER=postgres
POSTGRES_PASSWORD=choose-your-own
Add .env.* to .gitignore, so the file stays on your machine. Start the database with:
docker compose -f infra.compose.yml --env-file .env.dev up -d
One gotcha: two servers on port 5432
If PostgreSQL is also installed directly on your machine, it listens on 5432 too. Another container isn’t affected, because it reaches this one by name. A tool on your machine is: a database client connecting to localhost:5432 can reach the local server instead of the container, and there is no error. You open the database, and it isn’t the one the API uses.
The fix is to map a different host port, such as "5433:5432", and connect to that port from your machine. The container still listens on 5432 inside, so another container reaching it by name (Host=database-postgres;Port=5432) doesn’t change.
Check that it works
Build the solution:
dotnet build EcommerceApp.slnx
Then check the database container:
docker compose -f infra.compose.yml --env-file .env.dev ps
database-postgres should show as healthy. The migration files are in Ecommerce.Infrastructure/Migrations, but they haven’t run, so the database has no tables yet.
The full code at the end of this part is at series-part-4.