LESSON 8 OF 22

8. Configuring DbContext and EF Core in the Infrastructure Layer

Configure the SQL Server connection, create ApplicationDbContext in the Infrastructure layer, and isolate EF Core dependencies from the application core.

45 dk 112

Introduction

In the previous lessons, we separated the responsibilities of the Domain and Application layers, defined repository contracts, and prepared query and pagination models. In this lesson, we will begin implementing the database infrastructure behind those contracts.

EF Core is an ORM that maps application entities to relational database structures. However, Clean Architecture does not mean placing EF Core at the center of the application. The database provider, connection string, DbContext, and EF Core configuration should remain in the Infrastructure layer.

With this design, the Domain layer does not know about SQL Server, EF Core, or any ORM. The Application layer works only with repository and service contracts. SQL Server-specific details remain at the outer edge of the system.

The Position of DbContext in Clean Architecture

DbContext is EF Core's unit of work between the application and the database. It exposes entity sets through DbSet properties, executes queries, tracks changes, and sends updates to the database.

The recommended responsibility distribution for this project is:

  • Domain: Entities and business rules. It does not reference EF Core.
  • Application: Use cases, DTOs, and repository contracts.
  • Infrastructure: ApplicationDbContext, EF Core configurations, repository implementations, and the SQL Server provider.
  • Presentation/API: Receives HTTP requests and invokes registration methods exposed by Infrastructure.

In ASP.NET Core applications, a DbContext registered with AddDbContext uses a scoped lifetime by default. This is a suitable starting point for most web applications because one HTTP request can represent one unit of work. The same DbContext instance should not be used for parallel operations.

Required NuGet Packages

Select the Infrastructure project and add the SQL Server provider and EF Core design tools:

dotnet add CleanArchitecture.Infrastructure package Microsoft.EntityFrameworkCore.SqlServer --version 10.0.0
dotnet add CleanArchitecture.Infrastructure package Microsoft.EntityFrameworkCore.Design --version 10.0.0

Keep package versions compatible with the .NET and EF Core versions used by the solution. The Microsoft.EntityFrameworkCore.SqlServer package provides the UseSqlServer extension method.

Creating ApplicationDbContext

Create a Persistence folder in the Infrastructure project. Then add the ApplicationDbContext class:

using CleanArchitecture.Domain.Entities;
using Microsoft.EntityFrameworkCore;

namespace CleanArchitecture.Infrastructure.Persistence;

public sealed class ApplicationDbContext
    : DbContext
{
    public ApplicationDbContext(
        DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Product> Products => Set<Product>();
    public DbSet<Category> Categories => Set<Category>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.ApplyConfigurationsFromAssembly(
            typeof(ApplicationDbContext).Assembly);
    }
}

The DbContextOptions<ApplicationDbContext> constructor parameter is provided by Dependency Injection. Instead of hard-coding a connection string in this class, it should be read from application configuration during startup.

The DbSet properties represent tables or entity sets in the database. The expression-bodied form using Set<T>() allows EF Core to manage the sets through the context. You can also use the traditional property form:

public DbSet<Product> Products { get; set; } = null!;

Separating Entity Configurations

Keeping every table and column setting inside OnModelCreating may seem convenient at first. As the project grows, however, the DbContext becomes difficult to maintain. We will therefore create a separate configuration class for each entity.

using CleanArchitecture.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace CleanArchitecture.Infrastructure.Persistence.Configurations;

public sealed class ProductConfiguration
    : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> builder)
    {
        builder.ToTable("Products");

        builder.HasKey(product => product.Id);

        builder.Property(product => product.Name)
            .HasMaxLength(150)
            .IsRequired();

        builder.Property(product => product.Price)
            .HasPrecision(18, 2)
            .IsRequired();

        builder.HasOne(product => product.Category)
            .WithMany(category => category.Products)
            .HasForeignKey(product => product.CategoryId)
            .OnDelete(DeleteBehavior.Restrict);
    }
}

You can create a similar CategoryConfiguration class. The ApplyConfigurationsFromAssembly call discovers and applies implementations of IEntityTypeConfiguration<T> in the assembly. As a result, the DbContext remains a composition point instead of becoming a large configuration file.

Configuring the Connection String

Add the connection string to the API project's appsettings.json file:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=CleanArchitectureDb;Trusted_Connection=True;TrustServerCertificate=True;"
  }
}

LocalDB can be used during development. Production environments should use an actual SQL Server instance, Azure SQL, or another securely managed database service. Connection strings containing passwords must not be committed to source control.

Different values can be supplied with appsettings.Development.json, environment variables, Secret Manager, or Azure Key Vault. As long as the key remains ConnectionStrings:DefaultConnection, the application code can work across environments without changes.

Creating an Infrastructure DI Extension

Instead of spreading Infrastructure registrations throughout Program.cs, create an extension method inside the Infrastructure project:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace CleanArchitecture.Infrastructure;

public static class InfrastructureServiceRegistration
{
    public static IServiceCollection AddInfrastructure(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        var connectionString = configuration
            .GetConnectionString("DefaultConnection")
            ?? throw new InvalidOperationException(
                "DefaultConnection connection string was not found.");

        services.AddDbContext<ApplicationDbContext>(options =>
        {
            options.UseSqlServer(connectionString);
        });

        return services;
    }
}

Adjust namespaces to match your solution. Then call the method from the API project's Program.cs file:

using CleanArchitecture.Infrastructure;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddInfrastructure(
    builder.Configuration);

builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();
app.Run();

With this approach, the Presentation layer knows only the registration method exposed by Infrastructure. SQL Server configuration details are not scattered through the API startup code.

Preparing for Repository Implementations

In the next step, repository contracts from the Application layer will be implemented in Infrastructure. A simple example may look like this:

public sealed class ProductRepository
    : IProductRepository
{
    private readonly ApplicationDbContext _context;

    public ProductRepository(ApplicationDbContext context)
    {
        _context = context;
    }

    public Task<Product?> GetByIdAsync(
        Guid id,
        CancellationToken cancellationToken)
    {
        return _context.Products
            .Include(product => product.Category)
            .FirstOrDefaultAsync(
                product => product.Id == id,
                cancellationToken);
    }
}

The repository depends on DbContext, while the Application layer knows only the IProductRepository interface. This is a practical application of the Dependency Inversion Principle.

Common Mistakes

  • Hard-coding the connection string in DbContext: This makes environment changes and testing more difficult.
  • Adding EF Core to the Domain project: The Domain becomes coupled to a database technology.
  • Registering DbContext as a singleton: DbContext is not thread-safe, and a long lifetime can create tracking and memory problems.
  • Ignoring entity configurations: Column lengths, precision, and relationships may be generated with unsuitable defaults.
  • Putting secrets in appsettings.json: Production passwords and credentials should be stored through secure secret-management mechanisms.
  • Running parallel queries on one DbContext: Starting multiple asynchronous operations on the same context can cause runtime errors.

Short Practice Exercise

  1. Add the SQL Server and Design packages to the Infrastructure project.
  2. Create ApplicationDbContext and define DbSet properties for the existing Domain entities.
  3. Write at least one IEntityTypeConfiguration<T> class.
  4. Add DefaultConnection to the development configuration.
  5. Create the AddInfrastructure extension method and call it from the API.
  6. Run the application and verify that a meaningful error is produced when the connection string is missing.

Conclusion

In this lesson, we isolated EF Core and SQL Server inside the Infrastructure layer instead of placing database concerns at the center of the application. We created ApplicationDbContext, defined entity sets with DbSet, moved entity mappings into separate configuration classes, and registered the context through Dependency Injection.

The foundation is now ready to connect the repository contracts in the Application layer to a real database. In the next lesson, we will work with migrations and create the database schema from the EF Core model.

Sources