Clean Architecture and DDD in Legacy .NET Code, Incrementally
Apply Clean Architecture and DDD to legacy .NET code one bounded context at a time: pull rules out of stored procedures and skip the risky rewrite.
By Victor Sanchez
When teams try to bring Clean Architecture and DDD into a legacy codebase, they usually meet the same shape: the business rules are scattered between button-click handlers, a few thousand lines of stored procedures and a "Utils" project nobody wants to touch. Someone has drawn a beautiful diagram, and the team has been told to "move to DDD". Six months later there are four new projects in the solution, every class has an interface, and the rules still live in the stored procedures.
We have migrated systems to .NET 8 with DDD and Clean Architecture, and today we build enterprise applications with a .NET back end that uses DDD, Unit of Work and EF Core. What worked was never the big redesign. It was one bounded context at a time, with the domain logic pulled out where it actually lives.
What do Clean Architecture and DDD mean in legacy code?
- Clean Architecture is about dependency direction: the domain knows nothing about the database, the UI or the framework. Infrastructure depends on the core, never the other way around.
- DDD is about modeling: a bounded context is a part of the business with its own language and rules (for example, lending vs. treasury). Inside it, aggregates protect their invariants.
- Incremental means the legacy app keeps running and starts calling the new core for one context, while everything else stays as it is.
How to introduce DDD into a legacy codebase, step by step
1. Pick one bounded context
Choose an area with high change frequency and clear rules, not the scariest module. Good candidates have a known business owner and a steady stream of bugs. Map its vocabulary with that owner: if the business says "disbursement", the code should not say "TransactionType 4".
2. Create the core projects for that context only
src/
Lending.Domain/ // entities, value objects, domain rules (no EF, no ASP.NET)
Lending.Application/ // use cases, ports (interfaces), DTOs
Lending.Infrastructure/ // EF Core DbContext, repositories, external services
Legacy.Web/ // existing app, now calls Lending.Application for this contextThe legacy app references Lending.Application. It does not get rewritten; its event handlers just stop containing rules.
3. Pull the rules out of the UI and the stored procedures
Read the stored procedure line by line and turn each IF ... RAISERROR into a named rule on the aggregate. Leave set-based reporting queries in SQL, where they belong; move decisions into the domain. Any SQL that stays must be parameterized, as explained in stop concatenating SQL.
public sealed class Loan
{
private readonly List<Disbursement> _disbursements = new();
public LoanId Id { get; private set; }
public Money ApprovedAmount { get; private set; }
public LoanStatus Status { get; private set; }
public IReadOnlyList<Disbursement> Disbursements => _disbursements;
public Money DisbursedTotal =>
_disbursements.Aggregate(Money.Zero(ApprovedAmount.Currency), (sum, d) => sum + d.Amount);
// The rule used to live in a 400-line stored procedure
public void Disburse(Money amount, DateOnly date)
{
if (Status != LoanStatus.Approved)
throw new DomainException("Only approved loans can be disbursed.");
if (DisbursedTotal + amount > ApprovedAmount)
throw new DomainException("Disbursement exceeds the approved amount.");
_disbursements.Add(new Disbursement(amount, date));
}
}Before deleting the procedure, run both versions against the same data and compare results. That comparison is your proof that the extraction preserved behavior.
4. Add ports, a repository per aggregate and one unit of work
// Application layer: ports only, no EF Core types
public interface ILoanRepository
{
Task<Loan?> GetAsync(LoanId id, CancellationToken ct);
}
public interface IUnitOfWork
{
Task<int> SaveChangesAsync(CancellationToken ct);
}
public sealed class DisburseLoanHandler(ILoanRepository loans, IUnitOfWork uow)
{
public async Task HandleAsync(DisburseLoan cmd, CancellationToken ct)
{
var loan = await loans.GetAsync(cmd.LoanId, ct)
?? throw new NotFoundException(cmd.LoanId);
loan.Disburse(cmd.Amount, cmd.Date);
await uow.SaveChangesAsync(ct); // one transaction per use case
}
}// Infrastructure: the DbContext already is the unit of work
public sealed class LendingDbContext(DbContextOptions<LendingDbContext> options)
: DbContext(options), IUnitOfWork
{
public DbSet<Loan> Loans => Set<Loan>();
}
public sealed class LoanRepository(LendingDbContext db) : ILoanRepository
{
public Task<Loan?> GetAsync(LoanId id, CancellationToken ct) =>
db.Loans.Include(l => l.Disbursements)
.SingleOrDefaultAsync(l => l.Id == id, ct);
}Repositories exist per aggregate root, not per table, and they return aggregates, not IQueryable. The unit of work is the EF Core DbContext exposed through a small interface, so each use case commits once.
5. When do MediatR and CQRS pay off?
A plain handler class injected by DI is enough for most contexts. A mediator starts to pay off when you need the same cross-cutting behavior (validation, logging, transactions) on dozens of handlers. Separate read models (CQRS) pay off when reads and writes really have different shapes or scaling needs (we cover the basics in what the CQRS pattern is). If you adopt a library, check its current license terms first: some popular .NET libraries have moved to commercial licensing.
What are the common pitfalls?
- Interface for everything. Abstract the things that change or that you need to fake in tests (persistence, clock, external APIs), not every class.
- Generic repository over EF Core.
IRepository<T>withGetAll()rebuilds whatDbSetalready does and leaks queries everywhere. - Anemic domain. Entities with only getters and setters, plus "services" that hold all the rules, are the old code with more files.
- Two sources of truth. If a rule exists in both the procedure and the aggregate, they will drift. Remove the old one as soon as the comparison passes.
- The big-bang redesign. Migrating every context at once multiplies the risk and delays all feedback.
Checklist
- One bounded context chosen, with a business owner and a shared vocabulary.
- Domain project has no reference to EF Core, ASP.NET or WinForms.
- Each rule extracted from a procedure or handler has a named method and a test.
- Old and new implementations were compared on real data before removing the old one.
- Repositories are per aggregate; one
SaveChangesper use case. - Mediator or CQRS only where a concrete need was written down.
Key takeaways
- Clean Architecture is a dependency rule, not a folder template.
- Start with one bounded context and let the legacy app call into it.
- Move decisions out of stored procedures; keep set-based queries in SQL.
- EF Core's
DbContextalready is a unit of work; don't wrap it twice. - Add patterns when they solve a problem you can name.
This post builds on our .NET Framework to modern .NET migration playbook.
Sources
- Common web application architectures (Microsoft Learn)
- DDD and CQRS patterns in microservices (Microsoft Learn)
- Designing the infrastructure persistence layer
- Transactions in EF Core
- Bounded Context (Martin Fowler)
Need help bringing Clean Architecture to a legacy system?
Santhor modernizes legacy .NET systems, fixes performance problems and bugs in existing applications, and builds new software from scratch. We are based in Costa Rica and work nearshore with teams in the U.S. and Latin America. We can help you carve out the first bounded context and move it safely. Tell us about your project.