
In Part 1 of our C# & .NET Series, we built a single-project application with Models/ and Services/ folders. Now consider a real enterprise platform with 80 database tables, Redis caching, background workers, SMTP email services, and hundreds of API endpoints. If you put all of that inside a single .csproj project, database SQL queries and HTTP controllers inevitably tangle into unmaintainable spaghetti code.
In this masterclass, we scaffold a production 4-Layer Clean Architecture Solution in .NET 9 from scratch—inspecting the complete folder and file tree, writing the code for every layer, configuring Dependency Injection lifetimes, and mapping PostgreSQL tables with Entity Framework Core.
What We Will Build Step-by-Step:
1. Complete 4-Layer Solution Directory Tree (Domain,Application,Infrastructure,WebApi).
2. Terminal CLI commands to create the solution, wire inward project references, and install NuGet packages.
3. File-by-file C# code across all 4 layers (Product.cs,IProductRepository.cs,CommerceDbContext.cs,EfProductRepository.cs).
4. Dependency Injection Lifetimes:AddScopedvs.AddTransientvs.AddSingleton.
5. Generating and applying PostgreSQL schema migrations withdotnet ef.
1. The Complete Enterprise .NET 9 Solution Directory Tree
DigitalHat.Commerce/ # ROOT SOLUTION FOLDER
├── DigitalHat.Commerce.sln # Solution file grouping all projects
└── src/
├── 1. DigitalHat.Commerce.Domain/ # [LAYER 1 - CORE] Zero external package dependencies!
│ ├── DigitalHat.Commerce.Domain.csproj
│ ├── Common/BaseEntity.cs
│ ├── Entities/
│ │ ├── Product.cs # Core business entity & stock invariants
│ │ └── Order.cs
│ └── Enums/OrderStatus.cs
│
├── 2. DigitalHat.Commerce.Application/ # [LAYER 2 - USE CASES] References ONLY Domain!
│ ├── DigitalHat.Commerce.Application.csproj
│ ├── Abstractions/Repositories/
│ │ └── IProductRepository.cs # Persistence contract (Interface)
│ └── DTOs/ProductDtos.cs
│
├── 3. DigitalHat.Commerce.Infrastructure/ # [LAYER 3 - INFRA & DB] EF Core, PostgreSQL, SMTP, Redis
│ ├── DigitalHat.Commerce.Infrastructure.csproj
│ └── Persistence/
│ ├── CommerceDbContext.cs # EF Core DbContext (DbSet<Product>)
│ ├── Migrations/ # Auto-generated SQL schema migrations
│ └── Repositories/
│ └── EfProductRepository.cs # PostgreSQL implementation of IProductRepository
│
└── 4. DigitalHat.Commerce.WebApi/ # [LAYER 4 - HTTP PRESENTATION] Controllers & Middleware
├── DigitalHat.Commerce.WebApi.csproj
├── appsettings.json # PostgreSQL ConnectionString
├── Program.cs # DI composition root & HTTP pipeline
└── Controllers/ProductsController.cs
2. CLI Commands to Scaffold the 4-Layer Solution
mkdir DigitalHat.Commerce && cd DigitalHat.Commerce
dotnet new sln -n DigitalHat.Commerce
dotnet new classlib -n DigitalHat.Commerce.Domain -o src/DigitalHat.Commerce.Domain
dotnet new classlib -n DigitalHat.Commerce.Application -o src/DigitalHat.Commerce.Application
dotnet new classlib -n DigitalHat.Commerce.Infrastructure -o src/DigitalHat.Commerce.Infrastructure
dotnet new webapi -n DigitalHat.Commerce.WebApi -o src/DigitalHat.Commerce.WebApi --use-controllers
# Enforce the Dependency Rule (All arrows point inward toward Domain):
dotnet add src/DigitalHat.Commerce.Application reference src/DigitalHat.Commerce.Domain
dotnet add src/DigitalHat.Commerce.Infrastructure reference src/DigitalHat.Commerce.Application
dotnet add src/DigitalHat.Commerce.WebApi reference src/DigitalHat.Commerce.Application src/DigitalHat.Commerce.Infrastructure
dotnet sln add src/**/*.csproj
dotnet add src/DigitalHat.Commerce.Infrastructure package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add src/DigitalHat.Commerce.WebApi package Microsoft.EntityFrameworkCore.Design
3. File-by-File Implementation Across All 4 Layers
Layer 1 (Domain): src/DigitalHat.Commerce.Domain/Entities/Product.cs
using System;
namespace DigitalHat.Commerce.Domain.Entities;
public class Product
{
public Guid Id { get; private set; } = Guid.NewGuid();
public string Name { get; private set; } = default!;
public string Sku { get; private set; } = default!;
public decimal UnitPrice { get; private set; }
public int StockQuantity { get; private set; }
public bool IsActive { get; private set; } = true;
public DateTimeOffset CreatedAt { get; private set; } = DateTimeOffset.UtcNow;
private Product() { } // Required by EF Core materialization
public Product(string name, string sku, decimal unitPrice, int stockQuantity)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Product name is required.", nameof(name));
if (unitPrice <= 0)
throw new ArgumentOutOfRangeException(nameof(unitPrice), "Unit price must be greater than zero.");
if (stockQuantity < 0)
throw new ArgumentOutOfRangeException(nameof(stockQuantity), "Stock cannot be negative.");
Name = name.Trim();
Sku = sku.Trim().ToUpperInvariant();
UnitPrice = unitPrice;
StockQuantity = stockQuantity;
}
public void DecreaseStock(int quantity)
{
if (quantity <= 0) throw new ArgumentOutOfRangeException(nameof(quantity));
if (StockQuantity < quantity)
throw new InvalidOperationException($"Insufficient stock for {Name}. Available: {StockQuantity}");
StockQuantity -= quantity;
}
}
Layer 2 (Application): Abstractions/Repositories/IProductRepository.cs
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using DigitalHat.Commerce.Domain.Entities;
namespace DigitalHat.Commerce.Application.Abstractions.Repositories;
public interface IProductRepository
{
Task<Product?> GetByIdAsync(Guid id, CancellationToken ct = default);
Task<IReadOnlyList<Product>> GetAllActiveAsync(CancellationToken ct = default);
Task AddAsync(Product product, CancellationToken ct = default);
Task SaveChangesAsync(CancellationToken ct = default);
}
Layer 3 (Infrastructure): CommerceDbContext.cs & EfProductRepository.cs
using DigitalHat.Commerce.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace DigitalHat.Commerce.Infrastructure.Persistence;
public class CommerceDbContext : DbContext
{
public CommerceDbContext(DbContextOptions<CommerceDbContext> options) : base(options) { }
public DbSet<Product> Products => Set<Product>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>(builder =>
{
builder.ToTable("Products");
builder.HasKey(p => p.Id);
builder.Property(p => p.Name).IsRequired().HasMaxLength(200);
builder.Property(p => p.Sku).IsRequired().HasMaxLength(64);
builder.HasIndex(p => p.Sku).IsUnique();
builder.Property(p => p.UnitPrice).HasPrecision(18, 2);
});
}
}
4. Dependency Injection Lifetimes: Scoped vs. Transient vs. Singleton
| Lifetime | Instantiation Behavior | When to Use It |
|---|---|---|
AddScoped |
One instance per HTTP request; disposed when the request ends. | Mandatory for EF Core DbContext and Repositories. |
AddTransient |
New instance every time it is injected. | Stateless lightweight validators and mappers. |
AddSingleton |
Single instance shared across the entire process lifetime. | Thread-safe in-memory caches, Redis multiplexers, configuration readers. |
Did you find this engineering guide helpful?
Give it a like or share it with your team and network.