Dependency Injection and Layering¶
Rule prefix: DI · Baseline: C# 14 / .NET 10 · Levels: DO · DO NOT · CONSIDER · AVOID
Home · Rule index · Naming cheat sheet
This chapter covers how a class receives its dependencies and how a web endpoint hands its work to the rest of the application: constructor injection, service lifetimes, captive dependencies, startup validation of the container, and thin endpoints. It uses the built-in container (Microsoft.Extensions.DependencyInjection) and the built-in ASP.NET Core shapes (minimal APIs, controllers, TypedResults, ProblemDetails). It does not cover third-party containers, keyed services, the options pattern, project and folder structure, mediator or CQRS libraries, validation frameworks, or how to design the application services themselves.
General rules are linked, not repeated. Primary constructors are set by LANG-012, disposal of objects you create yourself by ERR-020, HttpClient creation through the factory by ERR-022, and the CancellationToken parameter by ASYNC-012. The names of contexts and query methods are on page 14.
No .NET SDK analyzer checks the rules in this chapter, so every rule is a manual rule: reviewers check it, and it is listed in the "Manual review only" table on page 15 (TOOL-018). The container itself checks one thing at run time (DI-013), which is a switch you turn on, not an analyzer.
The examples use sample-domain types that the page does not declare: Order (with Id, Total and Status), OrderStatus, Payment (with Id and Amount), IPaymentGateway, CardPaymentGateway, PaymentCapture, PaymentRetry, ExchangeRateCache, OrderNumberFormatter and OrderingDbContext. The examples are code from an ASP.NET Core (web) project, where Microsoft.Extensions.DependencyInjection and Microsoft.Extensions.Hosting are implicit using directives, so the examples do not repeat them.
Rule index¶
| ID | Level | Rule | Enforced |
|---|---|---|---|
| DI-010 | DO | take dependencies through the constructor (a primary constructor is fine, see LANG-012), and never resolve services from IServiceProvider inside business code (the service locator pattern). |
Manual |
| DI-011 | DO | register each service with the lifetime its state requires: singleton for stateless or thread-safe shared state, scoped for per-request or unit-of-work state (a DbContext), transient for lightweight stateless services. |
Manual |
| DI-012 | DO NOT | inject a scoped service, or a transient IDisposable, into a singleton (a captive dependency); create a scope with IServiceScopeFactory for each unit of work and resolve the service inside it. |
Manual |
| DI-013 | CONSIDER | turning on ValidateScopes and ValidateOnBuild in every environment, so that a captive dependency or a missing registration fails when the application starts. |
Manual |
| DI-020 | DO | keep an endpoint thin: bind and validate the input, call one application service, and map the outcome to an HTTP result with TypedResults (or Results) or ProblemDetails, with no data access and no business logic in the endpoint body. |
Manual |
Dependency injection¶
These rules cover how dependencies reach a class, how long each one lives, and how to catch lifetime mistakes at startup.
DI-010¶
DO take dependencies through the constructor (a primary constructor is fine, see LANG-012), and never resolve services from IServiceProvider inside business code (the service locator pattern).
✅ Correct
namespace Contoso.Orders;
public sealed class PaymentCapture(IPaymentGateway paymentGateway, TimeProvider timeProvider)
{
public Task<Payment?> CaptureAsync(int orderId, decimal amount, CancellationToken cancellationToken = default)
{
return paymentGateway.ChargeAsync(orderId, amount, timeProvider.GetUtcNow(), cancellationToken);
}
}
❌ Incorrect — the dependency is looked up at run time
namespace Contoso.Orders;
public sealed class PaymentCapture(IServiceProvider services)
{
public Task<Payment?> CaptureAsync(int orderId, decimal amount, CancellationToken cancellationToken = default)
{
var paymentGateway = services.GetRequiredService<IPaymentGateway>(); // service locator hides the dependency
return paymentGateway.ChargeAsync(orderId, amount, TimeProvider.System.GetUtcNow(), cancellationToken);
}
}
❌ Incorrect — the class creates its own dependency
namespace Contoso.Orders;
public sealed class PaymentCapture
{
private readonly CardPaymentGateway _paymentGateway = new(); // concrete dependency created inside the class
public Task<Payment?> CaptureAsync(int orderId, decimal amount, CancellationToken cancellationToken = default)
{
return _paymentGateway.ChargeAsync(orderId, amount, TimeProvider.System.GetUtcNow(), cancellationToken);
}
}
Why: The constructor is the list of what a class needs. A reader sees it at a glance, the container reports a missing registration before the object is used, and a test passes a fake straight to the constructor. A class that asks IServiceProvider for its dependencies hides that list: it compiles without the registration, fails on the first call that needs it, and a test must build a container to run it. The Microsoft guidance names this pattern as one to avoid, and calls injecting a factory that resolves dependencies at run time a variation of it. A class that creates its dependency with new is tied to one implementation and cannot be tested without it. A long constructor parameter list is a signal that the class has too many responsibilities, so split the class instead of switching to a locator. The primary-constructor form is the same mechanism with less code (LANG-012). No diagnostic reports a call to GetService or GetRequiredService in business code, so this is a manual rule.
Exceptions:
- The composition root (
Program.csand theAdd...extension methods that register services) works with the container directly. - The scope that DI-012 creates for one unit of work may resolve the one application service that runs the unit of work from
scope.ServiceProvider. - A type that the framework builds without the container, such as middleware, receives scoped services as parameters of its
InvokeAsyncmethod.
Scope: Constructors of classes that the container creates · Enforced: Manual · Sources: MS-DI-GUIDELINES, MS-DI-OVERVIEW, MS-ASPNET-DI
DI-011¶
DO register each service with the lifetime its state requires: singleton for stateless or thread-safe shared state, scoped for per-request or unit-of-work state (a DbContext), transient for lightweight stateless services.
✅ Correct
using Microsoft.EntityFrameworkCore;
namespace Contoso.Orders;
public static class OrderingServiceCollectionExtensions
{
public static IServiceCollection AddOrdering(this IServiceCollection services, string connectionString)
{
// Stateless and thread safe, so one instance serves the whole process.
services.AddSingleton(TimeProvider.System);
// Shared state held in a thread-safe collection.
services.AddSingleton<ExchangeRateCache>();
// The context holds the state of one unit of work, so it is scoped (this is also the default).
services.AddDbContext<OrderingDbContext>(options => options.UseSqlServer(connectionString));
// Performs the work of one request with the gateway and the clock, so it is scoped.
services.AddScoped<PaymentCapture>();
// Cheap to create and keeps no state.
services.AddTransient<OrderNumberFormatter>();
return services;
}
}
❌ Incorrect — per-request state with a process-wide lifetime, and shared state rebuilt on every request
namespace Contoso.Orders;
public static class OrderingServiceCollectionExtensions
{
public static IServiceCollection AddOrdering(this IServiceCollection services)
{
services.AddSingleton<OrderingDbContext>(); // per-unit-of-work state and not thread safe, held for the whole process
services.AddTransient<ExchangeRateCache>(); // shared cache that every consumer builds again
return services;
}
}
Why: The lifetime decides how long an instance lives and who can reach it. A scoped service is created once per request (or per scope you create) and disposed at its end. A singleton is created once and lives until the application stops, so concurrent requests all use it and it must be thread safe. A transient service is created each time it is requested, which costs an allocation per use. A DbContext tracks the entities of one unit of work and is not safe for concurrent use, so it belongs in a scope. AddDbContext registers it as scoped for that reason, and a service must not use a context whose lifetime is shorter than its own (DI-012). Microsoft's guidance advises a singleton only for a service that has its own state that is expensive to create or shared by everyone, and describes the singleton lifetime as common for stateless services. Read that as follows: a stateless service that is expensive to build, or that is safe to share, may be a singleton, and a stateless service that is cheap to build may be transient. When you are not sure that a service is thread safe, do not make it a singleton.
See also: ERR-022 (a typed HttpClient is registered through the factory, not as a singleton you create).
Scope: Service registrations (AddSingleton, AddScoped, AddTransient, AddDbContext) · Enforced: Manual · Sources: MS-DI-LIFETIMES, MS-DI-GUIDELINES, MS-ASPNET-DI
DI-012¶
DO NOT inject a scoped service, or a transient IDisposable, into a singleton (a captive dependency); create a scope with IServiceScopeFactory for each unit of work and resolve the service inside it.
✅ Correct — a singleton that opens a scope for each unit of work
namespace Contoso.Orders;
public sealed class PaymentRetryWorker(IServiceScopeFactory scopeFactory) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
await using AsyncServiceScope scope = scopeFactory.CreateAsyncScope();
var retry = scope.ServiceProvider.GetRequiredService<PaymentRetry>();
await retry.RunAsync(stoppingToken);
}
}
}
❌ Incorrect — a hosted service is a singleton, so the scoped service stays alive for the whole process
namespace Contoso.Orders;
// Registered with services.AddScoped<PaymentRetry>() and services.AddHostedService<PaymentRetryWorker>().
public sealed class PaymentRetryWorker(PaymentRetry retry) : BackgroundService // scoped service captured by a singleton
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
await retry.RunAsync(stoppingToken);
}
}
}
❌ Incorrect — a transient disposable captured by a singleton
namespace Contoso.Orders;
public sealed class ReceiptWriter : IDisposable
{
private readonly StringWriter _receipts = new();
public void Write(Payment payment)
{
_receipts.WriteLine(payment.Id);
}
public void Dispose()
{
_receipts.Dispose();
}
}
// Registered with services.AddTransient<ReceiptWriter>() and services.AddSingleton<ReceiptArchive>().
public sealed class ReceiptArchive(ReceiptWriter writer) // transient disposable lives as long as the process
{
public void Archive(Payment payment) => writer.Write(payment);
}
Why: A singleton is built once, so it receives each constructor argument once and keeps it. If that argument is scoped, the scoped service stops behaving as scoped: every request shares one instance, nobody disposes it until shutdown, and a DbContext captured this way keeps tracked entities from old requests, is used from several threads at once, and can show one user's data in another user's request. The container disposes a transient IDisposable only when the scope it was resolved from ends, and a singleton is resolved from the root, so the instance lives until the application stops; many such instances resolved from the root build up as a memory leak. Take an IServiceScopeFactory instead, create a scope for each unit of work (one loop pass, one message), resolve the application service inside the scope, and dispose the scope when the work ends (DI-010 lists this as an allowed use of the provider). For a transient disposable, register it as scoped, or inject a factory that creates it so the caller can dispose it. The opposite direction is fine: a scoped or transient service may use a singleton. Middleware is built once, so a scoped service goes in the parameters of InvokeAsync, not in the middleware constructor. DI-013 makes the container report a scoped service captured by a singleton at startup; a transient disposable captured by a singleton is found only in review.
Scope: Constructor parameters of singletons, hosted services and middleware · Enforced: Manual · Sources: MS-DI-LIFETIMES, MS-DI-GUIDELINES, MS-DI-OVERVIEW, MS-ASPNET-DI
DI-013¶
CONSIDER turning on ValidateScopes and ValidateOnBuild in every environment, so that a captive dependency or a missing registration fails when the application starts.
✅ Correct — a web application
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseDefaultServiceProvider(options =>
{
options.ValidateScopes = true;
options.ValidateOnBuild = true;
});
✅ Correct — code that builds the container itself
namespace Contoso.Orders;
public static class ContainerFactory
{
public static ServiceProvider Build(IServiceCollection services)
{
return services.BuildServiceProvider(new ServiceProviderOptions
{
ValidateScopes = true,
ValidateOnBuild = true,
});
}
}
❌ Incorrect — both checks switched off
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseDefaultServiceProvider(options =>
{
options.ValidateScopes = false; // a captive dependency is not reported
options.ValidateOnBuild = false; // a missing registration fails on the first request that needs it
});
Why: ValidateScopes makes the container throw when a scoped service is resolved from the root provider or injected into a singleton, which is the captive dependency of DI-012. ValidateOnBuild checks when the provider is built that every registered service can be created, so a missing registration fails at startup and not on the first request that reaches it. The host turns both checks on by default only in the Development environment (the default of ValidateOnBuild is the value of IsDevelopment), so a mistake that development tests do not exercise can reach production unseen. Setting both options for every environment moves the failure to startup, which is cheaper than a failure on a live request. The build-time check does not validate open generic registrations. The rule is CONSIDER because the checks add work at startup and when services are resolved. The container performs them at run time and no analyzer reports a missing option, so this is a manual rule.
Exceptions: A project that measures a startup or resolution cost it cannot accept may keep the options on only in Development and in an integration test that builds the host with the production configuration, as long as that test runs on every change.
Scope: Container construction (UseDefaultServiceProvider, BuildServiceProvider) · Enforced: Manual · Sources: MS-DI-OVERVIEW, MS-DI-GUIDELINES, MS-DI-VALIDATEONBUILD
Endpoints¶
This section covers what an HTTP endpoint does and what it hands off.
DI-020¶
DO keep an endpoint thin: bind and validate the input, call one application service, and map the outcome to an HTTP result with TypedResults (or Results) or ProblemDetails, with no data access and no business logic in the endpoint body.
✅ Correct — a minimal API endpoint
using Microsoft.AspNetCore.Http.HttpResults;
namespace Contoso.Orders;
public sealed record PayOrderRequest(decimal Amount);
public sealed record PaymentResponse(int PaymentId, decimal Amount);
public static class PaymentEndpoints
{
public static void MapPaymentEndpoints(this IEndpointRouteBuilder routes)
{
routes.MapPost("/orders/{orderId:int}/payments", PayOrderAsync);
}
private static async Task<Results<Ok<PaymentResponse>, NotFound, ValidationProblem>> PayOrderAsync(
int orderId, PayOrderRequest request, PaymentCapture capture, CancellationToken cancellationToken)
{
if (request.Amount <= 0)
{
return TypedResults.ValidationProblem(new Dictionary<string, string[]>
{
[nameof(PayOrderRequest.Amount)] = ["Amount must be greater than zero."],
});
}
Payment? payment = await capture.CaptureAsync(orderId, request.Amount, cancellationToken);
if (payment is null)
{
return TypedResults.NotFound();
}
return TypedResults.Ok(new PaymentResponse(payment.Id, payment.Amount));
}
}
✅ Correct — the same endpoint as a controller action
using Microsoft.AspNetCore.Mvc;
namespace Contoso.Orders;
[ApiController]
[Route("orders/{orderId:int}/payments")]
public sealed class PaymentsController(PaymentCapture capture) : ControllerBase
{
[HttpPost]
public async Task<ActionResult<PaymentResponse>> PayOrderAsync(
int orderId, PayOrderRequest request, CancellationToken cancellationToken)
{
if (request.Amount <= 0)
{
ModelState.AddModelError(nameof(PayOrderRequest.Amount), "Amount must be greater than zero.");
return ValidationProblem(ModelState);
}
Payment? payment = await capture.CaptureAsync(orderId, request.Amount, cancellationToken);
if (payment is null)
{
return NotFound(); // [ApiController] turns this 404 into a ProblemDetails body
}
return new PaymentResponse(payment.Id, payment.Amount);
}
}
❌ Incorrect — data access and a business rule in the endpoint body
using Microsoft.EntityFrameworkCore;
namespace Contoso.Orders;
public static class PaymentEndpoints
{
public static void MapPaymentEndpoints(this IEndpointRouteBuilder routes)
{
routes.MapPost("/orders/{orderId:int}/payments", async (
int orderId, PayOrderRequest request, OrderingDbContext context, CancellationToken cancellationToken) =>
{
Order? order = await context.Orders
.FirstOrDefaultAsync(o => o.Id == orderId, cancellationToken); // query inside the endpoint
if (order is null)
{
return Results.NotFound();
}
if (order.Status != OrderStatus.Open || request.Amount != order.Total) // business rule inside the endpoint
{
return Results.Problem(detail: "The order cannot be paid.", statusCode: StatusCodes.Status409Conflict);
}
order.Status = OrderStatus.Paid;
await context.SaveChangesAsync(cancellationToken); // data access inside the endpoint
return Results.Ok(new PaymentResponse(order.Id, request.Amount));
});
}
}
Why: An endpoint is the boundary between HTTP and the application. Its job is to turn a request into a method call and the outcome into a response. When the query and the payment rule live in the endpoint body, a test needs an HTTP host to check them, another endpoint or a background job cannot reuse them, and the endpoint grows with every new rule. The application service owns the rules and the data access, so a unit test calls it directly. TypedResults helpers return concrete types, so a return type such as Results<Ok<PaymentResponse>, NotFound, ValidationProblem> lets the compiler reject a result the handler did not declare, adds the response types to the OpenAPI description, and lets a test assert on the type without a server. Failures use the problem details format for HTTP APIs, which gives every error response the same shape: TypedResults.ValidationProblem and TypedResults.Problem for the endpoint, and AddProblemDetails with the exception-handler middleware for failures nobody anticipated (ERR-012 keeps the endpoint free of catch-all blocks). The shapes in this rule are the ones the framework ships; the rule reads the same for minimal APIs and controllers. Check the input shape in the endpoint (a required value, a range) and keep the business rules (the order is open, the amount matches) in the application service, which reports an expected failure without throwing (ERR-016). Authentication and authorization are configured outside these examples (a policy on the route or on the controller), and the application service still checks that the caller may act on this order. Never copy exception.Message or a stack trace into the detail of a problem details response, and use the developer exception page only in the Development environment (SEC-072).
House convention: Microsoft documents Results, TypedResults, Results<...> and problem details, and advises that controller classes focus on UI concerns and that a class with many injected dependencies has too many responsibilities. The limits in this rule, one application service per endpoint and no data access or business logic in the endpoint body, are this guide's convention, and no Microsoft page states them as a rule. When one request needs two application services, add one application service that calls both.
Exceptions: An endpoint that returns a constant or a health status, and calls no application service, has nothing to hand off.
See also: DI-010 (the service reaches the endpoint as a parameter, not through IServiceProvider), DATA-007 (data access in async code).
Scope: Minimal API handlers and controller actions · Enforced: Manual · Sources: MS-MINAPI-RESPONSES, MS-ASPNET-ERRORS, MS-ASPNET-DI, MS-DI-GUIDELINES
Related¶
- Language Features: LANG-012 (primary constructors).
- Exceptions and Error Handling: ERR-012 (catch only what you handle), ERR-016 (expected failures), ERR-020 (disposal) and ERR-022 (
HttpClientthrough the factory). - Secure Coding: SEC-072 (what an error response may contain).
- Async and Concurrency: ASYNC-012 (the
CancellationTokenparameter). - Data Access: DATA-001 (
DbContextnames) and DATA-007 (asynchronous data access). - Tooling and Enforcement: TOOL-018 (the manual review table).
Sources¶
The keys cited in this chapter are listed on the Sources page.
MS-DI-OVERVIEW, MS-DI-GUIDELINES, MS-DI-LIFETIMES, MS-ASPNET-DI, MS-MINAPI-RESPONSES, MS-ASPNET-ERRORS, MS-DI-VALIDATEONBUILD.
Previous: Tooling and Enforcement · Home · Next: Rule Cross-Reference