In an ASP.NET Core MVC action, when would you inject a dependency with [FromServices] or [FromKeyedServices] instead of the controller constructor?
answer
- only one action needs it
- resolved from HttpContext.RequestServices
- nullable means optional
- FromKeyedServices lives in Microsoft.Extensions.DependencyInjection
- not combinable with another source attribute
basics
~20 sUse them when only one action needs a dependency: the service is resolved from the request's scope for that action alone, and [FromKeyedServices("key")] picks one keyed registration. Dependencies every action uses still belong in the constructor.
solid answer
~40 s`[FromServices]` binds an action parameter from `HttpContext.RequestServices`, the request's DI scope, so a scoped service is the same instance the rest of the request sees. It suits a dependency that one action needs, such as an exporter used only by a report endpoint: the constructor would resolve it for every action. Nullability decides failure: a non-nullable parameter uses `GetRequiredService` and throws `InvalidOperationException` when nothing is registered; a nullable parameter or one with a default gets `null`. `[FromKeyedServices("fifo")]`, available since .NET 8 and defined in `Microsoft.Extensions.DependencyInjection`, resolves a keyed registration the same way. It cannot be combined with `[FromServices]` or another binding-source attribute on one parameter; MVC throws `NotSupportedException`. Service parameters are also excluded from model validation.
go deeper
Recognise [FromServices] on an action parameter and know it pulls the object from dependency injection rather than from the request.
Explain request-scope resolution, the nullable versus non-nullable behaviour, and how [FromKeyedServices("key")] selects one keyed registration.
Decide constructor versus action injection by cost and cohesion, and spot NotSupportedException from stacked source attributes in review.
Judge when keyed services per endpoint clarify a design and when a strategy or factory abstraction would keep controllers simpler.
## Two places to receive a dependency An ASP.NET Core MVC controller is created **per request** by default, and its constructor parameters are resolved from the request's DI scope. Action parameters can be resolved from the same scope when you mark them: - `[FromServices]` (namespace `Microsoft.AspNetCore.Mvc`) asks `HttpContext.RequestServices` for the parameter's type. - `[FromKeyedServices(key)]` (namespace `Microsoft.Extensions.DependencyInjection`) asks the same provider, cast to `IKeyedServiceProvider`, for the registration made under that key. Because both come from `RequestServices`, a **scoped** service bound into an action is the very instance the controller, filters and other services in that request already share. Neither attribute changes a lifetime; they only change where the resolution happens. ## When action injection is the better choice | Situation | Constructor | Action parameter | |---|---|---| | Every action uses the dependency | natural fit | repetitive | | One action out of many needs it | resolved for every action anyway | resolved only when that action runs | | The implementation varies by key per endpoint | needs one constructor parameter per key | `[FromKeyedServices("fifo")]` on the action that wants it | | The dependency is expensive to build | cost paid on every request to the controller | cost paid only where needed | A stock reporting controller illustrates it: listing adjustments needs a repository on every action, but only the valuation endpoint needs an `IStockValuation` and an optional exporter. ```csharp builder.Services.AddKeyedScoped<IStockValuation, FifoValuation>("fifo"); builder.Services.AddKeyedScoped<IStockValuation, AverageCostValuation>("average"); [HttpGet("api/warehouses/{warehouseId:int}/valuation")] public async Task<IActionResult> GetValuation( int warehouseId, [FromKeyedServices("fifo")] IStockValuation valuation, [FromServices] IStockReportExporter? exporter, CancellationToken cancellationToken) { var total = await valuation.ValueAsync(warehouseId, cancellationToken); return Ok(total); } ``` ## Required or optional MVC's services binder decides from the parameter's metadata: 1. A parameter that is **not annotated nullable** and has no default value is **required**. The binder calls `GetRequiredService` or `GetRequiredKeyedService`, and a missing registration throws `InvalidOperationException` during binding, which surfaces as a 500. 2. A **nullable** parameter such as `IStockReportExporter?`, or one with a default value, is **optional**. The binder calls `GetService` or `GetKeyedService` and passes `null` when nothing is registered. That makes optional collaborators explicit in the signature rather than hidden behind a service-locator call. ## Rules and limits - **One source per parameter.** Putting `[FromKeyedServices]` next to `[FromServices]`, `[FromQuery]` or any other binding-source attribute makes MVC throw `NotSupportedException` when it reads the parameter's binding info. - **No validation.** Service instances are marked to skip model validation, so DataAnnotations on a service type never add `ModelState` errors. - **Not a lifetime fix.** Controllers are not singletons; a scoped service is safe in a controller constructor. `[FromServices]` is about *which action pays* for resolution, not about lifetimes. - **Keys are compared by value.** The key object passed to `AddKeyedScoped` and to `[FromKeyedServices]` must be equal; a string key is the common choice. - **Inference.** Under `[ApiController]`, a parameter whose type is registered in DI can be inferred as a service without the attribute; that convention and its opt-out flag belong to controller conventions. Writing the attribute keeps the source obvious in either case. ## Version notes Keyed services and `[FromKeyedServices]` arrived with .NET 8; in ASP.NET Core 10 the same attribute serves MVC actions and Minimal API handlers. Registration (`AddKeyedSingleton`, `AddKeyedScoped`, `AddKeyedTransient`) is part of DI registration rather than binding. ## What interviewers listen for - The trade-off between constructor and action injection, not just the syntax. - That the parameter is resolved from the request scope. - How nullability turns a missing registration into either an exception or `null`. - The namespace of `FromKeyedServicesAttribute`, a common compile-time stumble.
- What happens at request time if a non-nullable [FromServices] parameter's type was never registered?MVC's services binder treats the parameter as required and calls `GetRequiredService`, which throws `InvalidOperationException` because no service of that type is registered. The exception escapes binding and becomes a 500. Declaring the parameter nullable, or giving it a default of `null`, makes the binder call `GetService` and pass `null` instead.
- Can you put [FromServices] and [FromKeyedServices] on the same parameter to be explicit?No. When MVC builds the parameter's binding info and finds `[FromKeyedServices]` together with any attribute that already sets a binding source, such as `[FromServices]` or `[FromQuery]`, it throws `NotSupportedException`. `[FromKeyedServices]` alone already sets the source to services.
- [FromServices] is required because MVC controllers are singletons and cannot take scoped services in constructors.
- A [FromServices] parameter gets a fresh scope of its own, separate from the request's.
- A missing registration for a non-nullable [FromServices] parameter just binds null.
- [FromKeyedServices] is in Microsoft.AspNetCore.Mvc alongside the other [From*] attributes.
- Combining [FromKeyedServices] with [FromServices] is the documented way to resolve a keyed service.
Assumes ASP.NET Core 10 on .NET 10; [FromKeyedServices] and keyed service registration exist since .NET 8 and are unchanged in 10.