.NET core features: DI, middleware, Minimal APIs, AOT
Most .NET services, whether a Web API, a background worker or a CLI tool, are assembled from the same few building blocks. Dependency injection wires objects together and controls how long they live. Middleware decides what happens to every HTTP request before and after your code runs. Minimal APIs map URLs to handlers with very little ceremony. Native AOT changes how the finished app is compiled and shipped. This page covers all four with one invented OrdersPortal service, so you can see how they fit together.
All samples are file-based programs for the .NET 10 SDK (dotnet run file.cs). The web samples start a server: run them with dotnet run file.cs --urls http://127.0.0.1:5123 and call them with curl. They were run with .NET SDK 10.0.115 on Linux x64.
Topics on this page
Section titled “Topics on this page”| Feature | Available since | Use it for |
|---|---|---|
| Dependency injection | .NET Core 1.0; keyed services in .NET 8 | Composing services and controlling their lifetime. |
| Middleware | ASP.NET Core 1.0 | Cross-cutting HTTP behavior: errors, auth, CORS, logging. |
| Minimal APIs | .NET 6; built-in validation in .NET 10 | HTTP endpoints without controllers. |
| Native AOT | Console apps in .NET 7; ASP.NET Core in .NET 8 | Fast startup and small, runtime-free executables. |
Dependency injection
Section titled “Dependency injection”Introduced with .NET Core 1.0, Microsoft.Extensions.DependencyInjection is the container behind ASP.NET Core, the Generic Host and worker services. You register services in an IServiceCollection and the container builds them, passing their dependencies to constructors. Classes then depend on interfaces, not on new, which keeps them testable and lets configuration choose implementations.
Every registration has a lifetime. A singleton is created once for the app. A scoped service is created once per scope; ASP.NET Core creates one scope per HTTP request, so a DbContext registered as scoped is shared by everything in that request and disposed at the end. A transient service is created every time it is resolved. .NET 8 added keyed services (AddKeyedScoped<T>("key") with [FromKeyedServices("key")]) for choosing between several implementations of one interface.
The container can check your wiring. ValidateScopes throws when a scoped service is resolved from the root provider, and ValidateOnBuild checks every registration can be built at startup. Both are on by default in the Development environment of ASP.NET Core apps; the sample turns them on explicitly.
#:package Microsoft.Extensions.DependencyInjection@10.0.0using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();services.AddSingleton<IClock, SystemClock>();services.AddScoped<OrderContext>(); // one per request or scopeservices.AddTransient<IOrderNumberGenerator, OrderNumberGenerator>();services.AddScoped<OrderService>();
using var provider = services.BuildServiceProvider(new ServiceProviderOptions{ ValidateScopes = true, // throw if a scoped service is resolved from the root ValidateOnBuild = true, // check every registration can be constructed});
for (int request = 1; request <= 2; request++){ using var scope = provider.CreateScope(); var first = scope.ServiceProvider.GetRequiredService<OrderService>(); var second = scope.ServiceProvider.GetRequiredService<OrderService>(); Console.WriteLine($"Request {request}: {first.Place("ORD")} | {second.Place("ORD")} | same context: {ReferenceEquals(first.Context, second.Context)}");}
try{ provider.GetRequiredService<OrderService>();}catch (InvalidOperationException ex){ Console.WriteLine($"Root resolve blocked: {ex.Message.Split('.')[0]}.");}
interface IClock { DateOnly Today { get; } }sealed class SystemClock : IClock { public DateOnly Today => new(2026, 11, 18); }
sealed class OrderContext { public Guid Id { get; } = Guid.NewGuid(); public int Count { get; set; } }
interface IOrderNumberGenerator { string Next(string prefix, int sequence); }sealed class OrderNumberGenerator(IClock clock) : IOrderNumberGenerator{ public string Next(string prefix, int sequence) => $"{prefix}-{clock.Today:yyyyMMdd}-{sequence:000}";}
sealed class OrderService(OrderContext context, IOrderNumberGenerator numbers){ public OrderContext Context => context; public string Place(string prefix) => numbers.Next(prefix, ++context.Count);}Output:
Request 1: ORD-20261118-001 | ORD-20261118-002 | same context: TrueRequest 2: ORD-20261118-001 | ORD-20261118-002 | same context: TrueRoot resolve blocked: Cannot resolve scoped service 'OrderService' from root provider.Each scope gets its own OrderContext, so the counter restarts per request, while both OrderService instances inside one scope share it.
Pitfalls:
- Captive dependencies. A singleton that takes a scoped service in its constructor keeps the first instance forever (a
DbContextshared across requests and threads). InjectIServiceScopeFactoryinto the singleton and create a scope per unit of work instead. - Service locator. Calling
GetRequiredServicefrom business code hides dependencies; prefer constructor injection and resolve only at composition points (endpoints, background loops). - Disposable transients. The container disposes
IDisposabletransients only when their scope ends, so resolving them from the root provider leaks them until shutdown.
Middleware
Section titled “Middleware”Middleware is ASP.NET Core’s request pipeline, there since ASP.NET Core 1.0. Each component receives the HttpContext, can do work, calls next to pass the request on, and can do more work as the response comes back. Components run in the order they are registered, so the first one registered is the outermost: it sees the request first and the response last. app.Use adds a component that calls next; app.Run adds a terminal component; app.Map branches the pipeline by path.
Order is therefore behavior. Microsoft’s recommended order for the built-in middleware is: exception handler and HSTS, HTTPS redirection, static files, routing, CORS, authentication, authorization, then your own middleware, then the endpoints. WebApplication adds routing and endpoint execution automatically, so a typical API only lists the ones it needs. Middleware is the right place for cross-cutting concerns that apply to many endpoints; business rules belong in services.
#:sdk Microsoft.NET.Sdk.Web#:property PublishAot=false
var builder = WebApplication.CreateBuilder(args);builder.Logging.ClearProviders(); // keep the console output readablebuilder.Services.AddProblemDetails();var app = builder.Build();
// 1. Outermost: turns unhandled exceptions into problem details responses.app.UseExceptionHandler();
// 2. Inline middleware: runs code before and after everything registered later.app.Use(async (context, next) =>{ var id = context.Request.Headers["X-Correlation-Id"].FirstOrDefault() ?? "generated-1"; context.Response.Headers["X-Correlation-Id"] = id; Console.WriteLine($"[{id}] -> {context.Request.Method} {context.Request.Path}"); await next(context); Console.WriteLine($"[{id}] <- {context.Response.StatusCode}");});
// 3. A branch that short-circuits: endpoints never run for /ping.app.Map("/ping", branch => branch.Run(ctx => ctx.Response.WriteAsync("pong")));
app.MapGet("/orders/{id:int}", (int id) => id == 13 ? throw new InvalidOperationException("Order store unavailable") : Results.Ok(new { id, status = "Shipped" }));
app.Run();Calls and responses (the traceId differs on every run):
$ curl http://127.0.0.1:5123/pingpong$ curl -H "X-Correlation-Id: abc-123" http://127.0.0.1:5123/orders/7{"id":7,"status":"Shipped"}$ curl -H "X-Correlation-Id: abc-124" http://127.0.0.1:5123/orders/13{"type":"https://tools.ietf.org/html/rfc9110#section-15.6.1","title":"An error occurred while processing your request.","status":500,"traceId":"..."}Server console:
[generated-1] -> GET /ping[generated-1] <- 200[abc-123] -> GET /orders/7[abc-123] <- 200[abc-124] -> GET /orders/13The last request has no <- line: the exception unwound through the logging middleware before the outer exception handler wrote the 500.
Pitfalls:
- Code after
nextis skipped on exceptions. Usetry/finallyfor anything that must run, and remember that inner middleware sees the exception, not the final status code. - Wrong order silently breaks features.
UseAuthorizationbeforeUseAuthenticationmeans no user is known when policies run;UseCorsafter the endpoints means preflight requests fail. - Writing after the response started. Changing headers after
nextreturns throws once the body has begun; set headers before callingnextor useResponse.OnStarting.
Minimal APIs
Section titled “Minimal APIs”Minimal APIs arrived in .NET 6 as a lightweight alternative to controllers: you map a route and HTTP method straight to a lambda or method with MapGet, MapPost and friends. Parameters bind automatically from the route, query string, headers, JSON body and DI container. TypedResults with a Results<T1, T2> return type makes every possible response visible to the compiler and to the OpenAPI document. MapGroup shares a route prefix, tags, filters and authorization across related endpoints.
.NET 10 added built-in validation: call builder.Services.AddValidation() and DataAnnotations attributes on parameters, classes and records are checked before the handler runs, with a 400 problem details response on failure. A source generator discovers the types, so validation only covers types used by endpoints in the assembly that calls AddValidation. Controllers remain fully supported and are still a good fit for large APIs that rely on filters, conventions and model binding features; see ASP.NET Core Web API for the controller style.
#:sdk Microsoft.NET.Sdk.Web#:property PublishAot=falseusing System.Collections.Concurrent;using System.ComponentModel.DataAnnotations;using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder(args);builder.Logging.ClearProviders();builder.Services.AddValidation(); // .NET 10: DataAnnotations for Minimal APIsbuilder.Services.AddProblemDetails();builder.Services.AddSingleton<OrderStore>();var app = builder.Build();
var orders = app.MapGroup("/api/orders").WithTags("Orders");
orders.MapGet("/{id:int}", Results<Ok<Order>, NotFound> (int id, OrderStore store) => store.Find(id) is { } order ? TypedResults.Ok(order) : TypedResults.NotFound());
orders.MapPost("/", Created<Order> (CreateOrder request, OrderStore store) =>{ var order = store.Add(request); return TypedResults.Created($"/api/orders/{order.Id}", order);});
app.Run();
public record CreateOrder( [Required, EmailAddress] string CustomerEmail, [Required, StringLength(40)] string Sku, [Range(1, 100)] int Quantity);
public record Order(int Id, string CustomerEmail, string Sku, int Quantity);
public sealed class OrderStore{ private readonly ConcurrentDictionary<int, Order> _orders = new(); private int _nextId = 1000;
public Order? Find(int id) => _orders.GetValueOrDefault(id);
public Order Add(CreateOrder request) { var order = new Order(Interlocked.Increment(ref _nextId), request.CustomerEmail, request.Sku, request.Quantity); _orders[order.Id] = order; return order; }}Calls and responses:
$ curl -i -X POST http://127.0.0.1:5123/api/orders -H "Content-Type: application/json" \ -d '{"customerEmail":"dana@example.test","sku":"KB-101","quantity":2}'HTTP/1.1 201 CreatedLocation: /api/orders/1001{"id":1001,"customerEmail":"dana@example.test","sku":"KB-101","quantity":2}
$ curl -X POST http://127.0.0.1:5123/api/orders -H "Content-Type: application/json" \ -d '{"customerEmail":"not-an-email","sku":"KB-101","quantity":0}'{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"errors":{"CustomerEmail":["The CustomerEmail field is not a valid e-mail address."],"Quantity":["The field Quantity must be between 1 and 100."]},"traceId":"..."}
$ curl -o /dev/null -w "%{http_code}\n" http://127.0.0.1:5123/api/orders/42404Pitfalls:
- Validation is opt-in. Without
AddValidation()the attributes are ignored and invalid input reaches the handler; nothing warns you at run time. - Endpoints in one huge
Program.cs. Group routes withMapGroupand move each group into an extension method (app.MapOrders()) once there are more than a handful. - File-based apps default to Native AOT. They publish with AOT, which turns off reflection-based JSON; anonymous types then fail to serialize. The web samples set
#:property PublishAot=false; see the next section for the AOT-friendly way.
Native AOT
Section titled “Native AOT”Native AOT compiles the app and the parts of the runtime it uses into a single native executable at publish time. It shipped for console apps in .NET 7 and for ASP.NET Core (Minimal APIs, gRPC, worker services) in .NET 8. The result is self-contained, starts much faster, uses less memory and needs no .NET runtime on the target machine, which matters most for many-instance cloud services, serverless functions, scale-to-zero containers and CLI tools.
The price is a closed world. There is no JIT, so nothing can generate code at run time: System.Reflection.Emit, loading assemblies dynamically and unbounded reflection are unavailable, and the app is trimmed, so code reached only through reflection may be removed. Use source generators instead: System.Text.Json source generation (JsonSerializerContext), the configuration binder generator, and the Minimal API request delegate generator. MVC controllers, Razor Pages, SignalR hubs in some modes and EF Core’s dynamic features are not fully compatible; check the compatibility table before choosing AOT. Enable it with <PublishAot>true</PublishAot> in the project (it also turns on AOT analyzers during build) and publish per platform with dotnet publish -c Release -r linux-x64. The build machine needs the platform’s native toolchain (on Linux, clang and zlib development files). dotnet new webapiaot creates an AOT-ready API using WebApplication.CreateSlimBuilder.
using System.Text.Json;using System.Text.Json.Serialization;
// Source-generated JSON metadata: no runtime reflection, so it works under Native AOT.var json = """[{"Id":1001,"Total":128.48,"Status":"Shipped"},{"Id":1002,"Total":189.00,"Status":"Pending"}]""";var orders = JsonSerializer.Deserialize(json, ReportJson.Default.OrderSummaryArray)!;
var report = new Report(orders.Length, orders.Sum(o => o.Total), orders.Count(o => o.Status == "Pending"));Console.WriteLine(JsonSerializer.Serialize(report, ReportJson.Default.Report));
record OrderSummary(int Id, decimal Total, string Status);record Report(int Orders, decimal Revenue, int Pending);
[JsonSerializable(typeof(OrderSummary[]))][JsonSerializable(typeof(Report))]partial class ReportJson : JsonSerializerContext;Publish and run (a file-based app enables Native AOT by default; in a project, set PublishAot in the .csproj):
$ dotnet publish orders-report.cs -r linux-x64 -o out Generating native code$ ./out/orders-report{"Orders":2,"Revenue":317.48,"Pending":1}$ du -h out/orders-report2.4M out/orders-reportPitfalls:
- Treat AOT warnings as errors. IL2xxx (trimming) and IL3xxx (AOT) warnings mean code that may fail at run time; publish early and often to see them, including warnings from libraries.
- One binary per platform. A Linux x64 build does not run on Arm64 or Windows, and a binary built on a newer Linux distribution may not run on an older one.
- Not always faster at steady state. AOT wins on startup and memory; a long-running JIT app can reach similar or higher throughput thanks to dynamic PGO. Measure before switching.
Choosing between them
Section titled “Choosing between them”These are not alternatives to each other: almost every ASP.NET Core service uses DI and middleware, and most new APIs use Minimal APIs. The real choices are within each feature:
- Lifetime: stateless and thread-safe → singleton; per-request state such as a
DbContextor the current user → scoped; cheap, stateful, short-lived helpers → transient. - Middleware or endpoint filter: applies to every request (errors, CORS, auth) → middleware; applies to a group of endpoints and needs their arguments → endpoint filter.
- Minimal APIs or controllers: new services, small to medium APIs and AOT targets → Minimal APIs; large existing controller code bases or heavy use of MVC filters and conventions → controllers.
- JIT or Native AOT: startup and memory dominate cost → AOT, if every dependency is compatible; otherwise JIT, optionally with ReadyToRun.
Interview questions
Section titled “Interview questions”What happens if a singleton depends on a scoped service?
The scoped instance is captured for the life of the app, so state meant for one request leaks across requests and threads. With ValidateScopes on (the default in Development) the container throws at resolution. Fix it by injecting IServiceScopeFactory and creating a scope per operation.
Why does middleware order matter? Give an example.
Each middleware wraps everything registered after it. If UseExceptionHandler is registered late, exceptions thrown by earlier middleware are not handled. If authorization runs before authentication, HttpContext.User is empty when policies are checked, so authenticated users get 401 or 403.
What is the difference between app.Use, app.Run and app.Map?
Use adds middleware that may call next; Run adds terminal middleware that never calls next; Map branches the pipeline for a path prefix, and the branch does not rejoin the main pipeline.
How do you validate input in a .NET 10 Minimal API?
Call AddValidation(), then annotate parameter types (classes or records) with DataAnnotations or implement IValidatableObject. Failures return 400 problem details before the handler runs; DisableValidation() opts an endpoint out.
What breaks when you turn on Native AOT?
Anything that needs run-time code generation or unbounded reflection: reflection-based JSON serialization, Reflection.Emit, dynamic assembly loading, some ORMs and DI patterns that scan assemblies. Replace them with source generators and fix all trim and AOT warnings.
Senior scenario: an OrdersPortal API on .NET 10 scales to zero in containers and cold starts take two seconds. Would you move it to Native AOT?
First measure where the time goes (startup trace, container pull time, first database connection). If JIT and assembly loading dominate, check AOT compatibility: Minimal APIs and source-generated JSON are fine, but MVC controllers or reflection-heavy libraries would need replacing. Try ReadyToRun first as a cheaper win, then prototype AOT with CreateSlimBuilder, publish in CI with warnings as errors, and compare cold start, memory and throughput under load before committing.
Related pages
Section titled “Related pages”- What is .NET?
- ASP.NET Core Web API: controllers, routing and pipeline
- Design patterns: creational patterns and DI
- .NET versions