ASP.NET Core MVC Intermediate

Injecting services into controllers and views

Once services are registered, controllers and views can use them. This lesson shows constructor injection in controllers, injecting into a single action with [FromServices], using @inject in Razor views, and reading settings with the options pattern.

How a controller gets its services
  1. StartServices registeredProgram.cs: AddScoped<IProductService, ProductService>()
  2. Step 2Request arrivesRouting selects ProductsController.Index
  3. Step 3Controller is createdMVC asks the container for a ProductsController
  4. Step 4Constructor parameters resolvedThe container creates or reuses IProductService
  5. Step 5Action runsThe service is ready in a private field
  6. EndViews can inject too@inject gives a view its own service

The idea in plain words

Controllers are created by the DI container, so any registered service can be a constructor parameter. Store it in a private readonly field and use it in your actions. If only one action needs a service, inject it into that action with [FromServices] instead. Views can request services with the @inject directive, which is handy for things like a list of countries for a drop-down.

Example: controller and options

The options pattern binds a configuration section to a class, then you inject IOptions<T>.

C#
public class ShopSettings
{
    public int PageSize { get; set; } = 20;
    public string SupportEmail { get; set; } = "";
}

// Program.cs
builder.Services.Configure<ShopSettings>(builder.Configuration.GetSection("Shop"));
builder.Services.AddScoped<IProductService, ProductService>();

public class ProductsController : Controller
{
    private readonly IProductService _products;
    private readonly ShopSettings _settings;

    public ProductsController(IProductService products, IOptions<ShopSettings> settings)
    {
        _products = products;
        _settings = settings.Value;
    }

    public async Task<IActionResult> Index(int page = 1)
        => View(await _products.GetPageAsync(page, _settings.PageSize));

    // Only this action needs the report builder
    public IActionResult Report([FromServices] IReportBuilder reports)
        => File(reports.Build(), "application/pdf", "report.pdf");
}

Example: injecting into a view

Razor
@* Views/Account/Register.cshtml *@
@inject ICountryService Countries
@model RegisterModel

<select asp-for="Country" asp-items="@(new SelectList(Countries.All()))"></select>

Common mistakes

  • Constructors with ten or more dependencies; that usually means the controller does too much. Move logic into services.
  • Using @inject in views to run business logic or database queries; views should only display.
  • Reading IConfiguration strings all over the code instead of strongly typed options.

Interview question

What is the options pattern in ASP.NET Core?

The options pattern binds a configuration section to a strongly typed class with services.Configure<T>(configuration.GetSection("Name")), and classes receive the settings through IOptions<T> (fixed values), IOptionsSnapshot<T> (recomputed per request, for scoped use) or IOptionsMonitor<T> (change notifications, usable in singletons). It keeps settings typed, testable and grouped, and supports validation.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.