LESSON 13 OF 22

13. Dependency Injection and Cross-Layer Service Registration

In this lesson, you will group Application and Infrastructure registrations into extension methods, complete DI configuration in the API project, and depend on interfaces instead of concrete classes.

40 dk 75

Introduction

In the previous lesson, we implemented the application services and business workflows. Our repositories, Unit of Work, and application service classes now contain real behavior. However, those classes cannot operate until their dependencies are registered in the Dependency Injection container when the application starts.

The goal of this lesson is not simply to add several AddScoped statements. In a professional Clean Architecture project, we need to decide which layer owns each registration, why the API project should not construct concrete implementations directly, and how extension methods can keep the composition root readable and maintainable.

ASP.NET Core includes a built-in DI container that creates services, resolves their dependencies, and manages them according to their configured lifetimes. Services are commonly registered as Transient, Scoped, or Singleton. In web applications, EF Core DbContext is normally scoped, so repositories and Unit of Work implementations that use it should usually be scoped as well.

DI Responsibilities by Layer

Clean Architecture responsibilities should also be reflected in dependency registration:

  • Domain: Contains business rules and core models. It should not depend on the DI container, EF Core, or ASP.NET Core.
  • Application: Contains use cases, DTOs, validators, application services, and repository contracts. It does not know Infrastructure implementations.
  • Infrastructure: Contains the DbContext, repository implementations, Unit of Work, and external service adapters. It implements contracts defined by the inner layers.
  • Presentation/API: Receives HTTP requests, reads configuration, and invokes the registration methods exposed by the other layers.

With this design, the API project should not directly create a ProductService instance. Instead, it should depend on IProductService. The registration method decides which implementation fulfills that contract.

Choosing Service Lifetimes

LifetimeBehaviorTypical usage in this project
TransientA new instance is created each time the service is requested.Small stateless helper services
ScopedOne instance is created within each HTTP request scope.DbContext, repositories, Unit of Work, application services
SingletonOne instance is shared for the lifetime of the application.Thread-safe services with no request-specific state

Injecting a scoped service directly into a singleton is invalid. For example, placing AppDbContext in the constructor of a singleton cache service can cause request-specific state to live longer than the request itself. Lifetime choices must therefore be evaluated across the entire dependency chain.

Creating the Application Registration Extension

Let us group the Application registrations first. Add a DependencyInjection folder and a ServiceCollectionExtensions.cs file to the Application project. The extension method returns IServiceCollection, which allows fluent calls from Program.cs.

using Microsoft.Extensions.DependencyInjection;
using CleanArchitecture.Application.Services;
using CleanArchitecture.Application.Services.Interfaces;

namespace CleanArchitecture.Application;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddApplicationServices(
        this IServiceCollection services)
    {
        services.AddScoped<IProductService, ProductService>();
        services.AddScoped<ICategoryService, CategoryService>();

        return services;
    }
}

This registration group contains only services owned by the Application layer. The Application project does not reference Infrastructure. As a result, application services remain independent from database and external technology implementations.

If FluentValidation validators are also located in the Application project, they can be registered in the same method:

using FluentValidation;

public static IServiceCollection AddApplicationServices(
    this IServiceCollection services)
{
    services.AddScoped<IProductService, ProductService>();
    services.AddScoped<ICategoryService, CategoryService>();
    services.AddValidatorsFromAssembly(typeof(ApplicationAssemblyMarker).Assembly);

    return services;
}

ApplicationAssemblyMarker can be an empty class used to locate the Application assembly. The API project then does not need to know the names of individual validators or services.

Creating the Infrastructure Registration Extension

Next, group the technical dependencies in the Infrastructure project. This method should accept the connection string configuration and register the DbContext, repositories, and Unit of Work.

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using CleanArchitecture.Application.Contracts.Persistence;
using CleanArchitecture.Infrastructure.Persistence;
using CleanArchitecture.Infrastructure.Repositories;

namespace CleanArchitecture.Infrastructure;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddInfrastructureServices(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        var connectionString = configuration.GetConnectionString("DefaultConnection");

        if (string.IsNullOrWhiteSpace(connectionString))
        {
            throw new InvalidOperationException(
                "DefaultConnection connection string is not configured.");
        }

        services.AddDbContext<AppDbContext>(options =>
            options.UseSqlServer(connectionString));

        services.AddScoped<IProductRepository, ProductRepository>();
        services.AddScoped<ICategoryRepository, CategoryRepository>();
        services.AddScoped<IUnitOfWork, UnitOfWork>();

        return services;
    }
}

This file exposes a registration operation without spreading Infrastructure implementation details across the API project. The API calls AddInfrastructureServices, while the concrete repository types remain inside Infrastructure.

Failing explicitly when the connection string is missing is safer than allowing the application to start with invalid configuration. An incorrect environment variable or incomplete appsettings file can then be detected immediately.

Combining Registrations in Program.cs

The API project's Program.cs should not contain every individual service registration. After adding the required project references, call the registration methods as follows:

using CleanArchitecture.Application;
using CleanArchitecture.Infrastructure;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services
    .AddApplicationServices()
    .AddInfrastructureServices(builder.Configuration);

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.MapControllers();

app.Run();

This creates a readable composition root. The registration groups used by the application are visible in Program.cs, while the internal details of each group remain in the appropriate layer.

Using Interfaces in Controllers and Services

The main benefit of DI appears in constructors. A controller should receive IProductService, not the concrete ProductService class:

[ApiController]
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }

    [HttpGet]
    public async Task<IActionResult> GetAll(CancellationToken cancellationToken)
    {
        var products = await _productService
            .GetAllAsync(cancellationToken);

        return Ok(products);
    }
}

Likewise, ProductService should depend on repository contracts and the Unit of Work abstraction:

public sealed class ProductService : IProductService
{
    private readonly IProductRepository _productRepository;
    private readonly IUnitOfWork _unitOfWork;

    public ProductService(
        IProductRepository productRepository,
        IUnitOfWork unitOfWork)
    {
        _productRepository = productRepository;
        _unitOfWork = unitOfWork;
    }

    public async Task<IReadOnlyList<ProductDto>> GetAllAsync(
        CancellationToken cancellationToken)
    {
        var products = await _productRepository
            .GetAllAsync(cancellationToken);

        return products.Select(ProductDto.FromEntity).ToList();
    }
}

Because these classes do not call new ProductRepository() or new ProductService(), replacing an implementation and writing unit tests become significantly easier.

Validating the Service Graph

Incorrect or missing registrations are often discovered when the application starts or when the first request is processed. In development, scope validation can help detect lifetime conflicts early:

builder.Host.UseDefaultServiceProvider((context, options) =>
{
    options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
    options.ValidateOnBuild = context.HostingEnvironment.IsDevelopment();
});

You can also perform a small smoke test to verify that a critical service can be resolved:

using (var scope = app.Services.CreateScope())
{
    var service = scope.ServiceProvider
        .GetRequiredService<IProductService>();
}

Resolving every service at startup is not always necessary, but checking important service graphs can expose missing registrations before real users send requests.

Common Mistakes

  • Depending on concrete classes: Injecting ProductService into a controller makes mocking and implementation replacement more difficult.
  • Registering everything as singleton: DbContext and repositories that use request-scoped data should not be singletons.
  • Registering services in the wrong layer: Registering Infrastructure classes inside Application reverses the intended dependency direction.
  • Not returning IServiceCollection: The extension method can no longer participate in fluent registration.
  • Missing project references: The API project must reference the projects that expose the registration extension methods.
  • Ignoring multiple implementations: When an interface has multiple registrations, a single service resolution generally selects the last registration; use IEnumerable<T> to resolve all implementations.
  • Injecting scoped services into singletons: This can break request scope behavior and cause runtime validation errors.

Practice Exercise

Complete the following exercise in the course project:

  1. Add the AddApplicationServices extension method to the Application project.
  2. Register at least two application services and their validators.
  3. Add the AddInfrastructureServices method to the Infrastructure project.
  4. Register the DbContext, two repositories, and Unit of Work with scoped lifetime.
  5. Call both registration methods from the API project's Program.cs.
  6. Use an interface instead of a concrete service in one controller constructor.
  7. Run the application and call an endpoint through Swagger.
  8. Temporarily remove one registration and inspect the resulting error.

As an additional task, write a unit test for an application service using a mock repository. The test should demonstrate that the service does not require the real database implementation.

Conclusion

In this lesson, we separated DI registrations according to layer responsibilities. We grouped Application and Infrastructure dependencies into extension methods, simplified Program.cs, and changed the API to depend on interfaces rather than concrete classes.

This approach supports the Clean Architecture dependency rule in practice: outer layers use contracts from inner layers, while inner layers remain unaware of external technologies. In the next lessons, we will build on this structure by adding validation, centralized exception handling, and safer API behavior.

Sources