Compares constructor, property and method injection, explains why Microsoft.Extensions.DependencyInjection supports only constructors, and shows where ASP.NET Core injects into methods and properties (endpoint parameters, [FromServices], InvokeAsync, @inject, [Inject]).
readonly.The built-in container supports constructor injection only, by design: it keeps dependencies explicit and resolution simple. ASP.NET Core adds method-level injection on top: Minimal API handler parameters, [FromServices] on MVC actions, and middleware InvokeAsync parameters. Razor's @inject and Blazor's [Inject] are framework-level property injection.
The trade-off: constructors make dependencies obvious, but a long constructor is a design smell you can't hide.
"Constructor injection is the default and the one I reach for. The class lists what it needs as constructor parameters, the container supplies them, and once the constructor returns the object is fully usable. Fields can be
readonly, there's no 'did someone set this yet' check, and the constructor documents the dependencies. Property injection means the container sets public properties after construction. It's meant for optional dependencies, but in practice it hides requirements and lets you get a half-built object. Method injection is passing the dependency into the specific method that uses it, which is great when only one operation needs it or when it varies per call.Microsoft's container only does constructor injection on purpose. It's meant to be the minimal common denominator that libraries can rely on, and constructors are explicit and fast to resolve. But ASP.NET Core itself does method injection in a few places: Minimal API handlers get services as parameters, MVC actions can take
[FromServices]parameters, and convention-based middleware is constructed once as a singleton, so scoped services go intoInvokeAsyncas parameters instead of the constructor. Razor views use@inject, and Blazor components use[Inject], which are property injection done by the framework, not the container.The mistake I see is people wanting property injection because a constructor has twelve parameters. That's the constructor telling you the class does too much. I'd rather split the class or introduce a facade than hide the dependencies."
| Form | How | Good for | Downsides |
|---|---|---|---|
| Constructor | Parameters on the constructor | Required dependencies (almost all) | Long constructors expose design smells (a feature) |
| Property | Settable public property | Truly optional dependencies, framework components | Half-initialised objects, hidden requirements, mutability |
| Method | Parameter on the method | One operation needs it, or it varies per call | Callers must supply it every time |
| Place | Mechanism | Why it exists |
|---|---|---|
| Minimal API handler | Service parameters inferred via IServiceProviderIsService |
Handlers are delegates, not classes |
| MVC action | [FromServices] parameter |
Avoid constructor bloat for one action's dependency |
| Convention-based middleware | InvokeAsync(HttpContext, IScopedService) |
Middleware instance is a singleton; scoped services must come per request |
| Razor view | @inject IFoo Foo |
Views are generated classes |
| Blazor component | [Inject] property |
Components are created by the renderer |
A convention-based middleware took a scoped TenantContext-style service in its constructor. Because middleware is created once, the first request's instance was captured and reused for every request, leaking one request's data into others in testing. Moving the dependency to an InvokeAsync parameter fixed it, and turning on ValidateScopes would have thrown at start-up.
Checks the candidate knows the three injection styles, why constructor injection is preferred, and the framework places where other styles appear.
Green flags
InvokeAsync rule for scoped servicesRed flags
A constructor is the one place where an object can enforce its invariants before anyone can use it:
public sealed class InvoiceService(IInvoiceRepository repo, TimeProvider clock)
{
// repo and clock are always set; no null checks in methods
}
It also makes the dependency graph visible to the container, so it can validate it (ValidateOnBuild) and detect cycles.
new InvoiceService() ← object exists but is unusable
.Logger = ... ← forgotten in one code path?
.Repository = ...
service.Create() ← NullReferenceException at run time
That ordering dependency is called temporal coupling. The built-in container won't do this at all; Autofac can (PropertiesAutowired()).
ASP.NET Core decides how to bind each handler parameter. For Minimal APIs it asks IServiceProviderIsService whether the type is a registered service; if yes, it resolves it from HttpContext.RequestServices (the request scope).
Request → endpoint delegate (int id, IOrderService orders, CancellationToken ct)
│ route │ RequestServices │ RequestAborted
For convention-based middleware, the constructor runs once at pipeline build time; InvokeAsync parameters after HttpContext are resolved from the request scope on every call. IMiddleware implementations are instead resolved from the container per request, so they can take scoped services in the constructor (register them as scoped or transient).
Use a null object (NullLogger<T>.Instance), a default registration with TryAdd, or a constructor parameter with a default value. All keep the object valid at construction.
ValidateScopes, and read the exception. Move the service to InvokeAsync.ILogger property to a class and resolve it from the built-in container; observe it stays null.Constructor injection for the class, method injection where the framework supports it.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IRequestAudit, RequestAudit>();
builder.Services.AddScoped<IOrderService, OrderService>();
var app = builder.Build();
app.UseMiddleware<AuditMiddleware>();
// Method injection: Minimal API handler parameters come from the request scope.
app.MapGet("/orders/{id:int}", async (int id, IOrderService orders, CancellationToken ct) =>
await orders.FindAsync(id, ct) is { } order ? Results.Ok(order) : Results.NotFound());
app.Run();
public interface IOrderService { Task<string?> FindAsync(int id, CancellationToken ct); }
// Constructor injection: required dependencies, object valid after construction.
public sealed class OrderService(TimeProvider clock) : IOrderService
{
public Task<string?> FindAsync(int id, CancellationToken ct) =>
Task.FromResult<string?>($"order {id} at {clock.GetUtcNow():O}");
}
public interface IRequestAudit { void Record(string path); }
public sealed class RequestAudit : IRequestAudit { public void Record(string path) { } }
// Convention-based middleware is a singleton: scoped services go in InvokeAsync, not the constructor.
public sealed class AuditMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context, IRequestAudit audit)
{
audit.Record(context.Request.Path);
await next(context);
}
}
// MVC equivalent: [FromServices] for a dependency only one action needs.
[ApiController, Route("api/reports")]
public sealed class ReportsController : ControllerBase
{
[HttpGet("gst")]
public IActionResult Gst([FromServices] IGstReportBuilder builder) => Ok(builder.Build());
}
InvokeAsync parameter, or implement IMiddleware.[FromServices] so that every action declares its own services. Why it is wrong: dependencies become scattered across action signatures and the controller's real dependencies are hard to see. Instead: use [FromServices] deliberately for a dependency that only one or two actions need (an expensive report builder, for example) and keep shared dependencies in the constructor.TryAdd.NullReferenceException, or silently skips behaviour. Instead: prefer constructor injection so the compiler forces every dependency to be supplied.readonly fields or primary constructor parameters.The senior view is that the injection style is a design decision, not a container feature. Constructor injection keeps objects valid and makes tests trivial: new InvoiceService(fakeRepo, fakeClock) with no container and no setup order to remember. Property injection makes tests fragile, because a test that forgets to set a property compiles and fails at run time. Method injection is the right call when the dependency genuinely varies per call or only one operation needs it, for example passing a CancellationToken, an IProgress<T> or a per-request strategy into a single method instead of storing it in the object.
Performance is a non-issue for the choice: after warm-up the container resolves constructor graphs with compiled delegates, and framework method injection is a lookup in the request scope. What matters is clarity and lifetime correctness, especially in middleware.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Constructor injection | Required dependencies, almost every service | Long constructors become visible | Values that vary per call |
Method injection (parameters, [FromServices], InvokeAsync) |
One operation needs it, per-call values, singleton middleware needing scoped services | Callers must supply it each time; can scatter dependencies if overused | Dependencies used by most methods of the class |
Property injection (@inject, [Inject], Autofac) |
Framework-created components, truly optional extras | Temporal coupling, harder tests | Required dependencies in your own services |
When you resolve a service, Microsoft.Extensions.DependencyInjection builds a call site: a tree describing how to create it (which constructor, which dependencies, which lifetime cache). It picks the constructor with the most parameters it can satisfy, and throws an InvalidOperationException if two equally long constructors are both satisfiable.
Call sites are cached per service type. Early resolutions are interpreted; once a service has been resolved repeatedly it is compiled in the background to an expression-tree or IL delegate, so later resolutions are a delegate call plus lifetime lookups.
GetService returns null for an unregistered type and GetRequiredService throws. ActivatorUtilities.CreateInstance builds a type that isn't registered, filling some constructor parameters from the container and others from arguments you pass.
The trade-off: the built-in container is fast and predictable but deliberately minimal.
Middleware is a component in the request pipeline: a RequestDelegate that receives the HttpContext, can do work, calls next to pass the request on, and can do more work when the response comes back. It can also short-circuit by not calling next. Use adds middleware that may call next; Run adds terminal middleware; Map branches the pipeline by path; UseWhen branches on a condition and rejoins, MapWhen branches without rejoining. Because each middleware wraps the next, order is behaviour: exception handling first, then HTTPS, static files, routing, CORS, authentication, authorisation and finally endpoints. Custom middleware can be convention-based (a class with InvokeAsync, created once as a singleton) or implement IMiddleware (resolved from DI per request). The trade-off: convention-based is the fastest default; IMiddleware is clearer when you need scoped dependencies.
Null Object replaces null with an object that implements the same interface and does nothing safely, so callers don't need null checks.
.NET uses it widely: NullLogger<T>.Instance, Stream.Null, TextWriter.Null, Array.Empty<T>(), Enumerable.Empty<T>(), Task.CompletedTask and CancellationToken.None. Returning an empty collection instead of null is the everyday form.
Nullable reference types solve a different problem: they make "this might be null" visible at compile time so you handle it. Null Object is for when "do nothing" is genuinely the correct behaviour, like an optional logger.
The danger is when doing nothing is wrong: a NullLogger left in production, or an empty list returned because the database call failed. Then the null object hides an error instead of preventing one.
Last updated 23 Nov 2026.