Search⌘ K
AI Features

Getting Services in Controllers and Views

Explore methods to inject services into ASP.NET Core MVC controllers and views. Understand when to inject services in constructors, action methods, or views, and learn about repository, aggregate, and unit-of-work patterns. This lesson helps you organize business logic cleanly by factoring it into command handlers, improving modularity and testability.

In this lesson, we will analyze the communication patterns between controllers and previous layers. However, we first need to list all the options we have for injecting service in controllers and views.

Injecting services in controllers and views

Controllers and Views are added to the dependency injection container, so all parameters of their constructors are automatically filled by the dependency injection engine.

We already experimented with injecting services in controllers’ constructors in the previous lesson. We just need to declare all services we need in the controller’s constructor.We can store them in private/protected fields so they can be used in all controllers’ methods.

However, services can also be injected directly into action methods. It is enough to declare them as action method parameters and precede them with the [FromServices] annotation. Thus, in the example of the previous lesson, we might have injected ICostumerRepository in each action method instead of ...

C#
[HttpPost]
public IActionResult Edit(Customer model, [FromServices] ICostumerRepository repo)
{
...
repo.Modify(model);
return RedirectToAction(nameof(HomeController.Index));
...
}

Which of the two techniques we ...