liveBook · Manning

FromServices attribute

As explained in ASP.NET Core in Action, 3e

The FromServices attribute is an ASP.NET Core parameter attribute that directs a handler parameter to be resolved from dependency injection services.

The [FromServices] attribute tells ASP.NET Core to provide an endpoint or handler parameter from a service registered in the dependency-injection container. It makes the binding source explicit instead of relying on framework conventions. section 7.6.2 section 16.2.3

Explicitly injecting LinkGenerator

app.MapGet("/links", ([FromServices] LinkGenerator links) => { string link = links.GetPathByName("products"); return $"View the product at {link}"; }); The handler receives LinkGenerator from dependency injection and uses it to create a product link. section 7.6.2 section 7.6.2

Minimal APIs can usually recognize registered services automatically, so adding the attribute is often unnecessary. It can improve clarity or help with some custom dependency-injection containers that do not support the conventions used by minimal APIs. section 7.6.2

app.MapGet("/links", ([FromServices] LinkGenerator links) =>

View the same LinkGenerator handler with [FromServices] applied directly to its parameter. section 7.6.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains explicit service binding, automatic detection, and a rare custom-container case without detailing container registration.
Examples
Uses LinkGenerator in a minimal API endpoint and contrasts explicit annotation with convention-based service resolution.
What it assumes
Assumes a service is registered in the dependency-injection container and teaches that minimal APIs can otherwise infer the service automatically.
What you can do after
Apply it via [FromServices] when a handler parameter should explicitly come from dependency injection.
How it connects
Connects dependency injection with model binding, minimal APIs, endpoint handlers, and Razor Pages handler parameters.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.