Getting Services in Controllers and Views
In this lesson, we will learn the various options for injecting services in controllers and views. We will also look at structured patterns of interaction between controllers and database or business layer that leverage the power of dependency injection.
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 injecting it in the constructor, as shown in the example below:
[HttpPost]public IActionResult Edit(Customer model, [FromServices] ICostumerRepository repo){...repo.Modify(model);return RedirectToAction(nameof(HomeController.Index));...}
Which of the two techniques we use is just a matter of modularity: if a service is used by just a single action method, inject it directly into that action method. If, the same service is used by several methods in the controller, it is best to inject it into the constructor.
For what concerns views, we don’t define any constructor when we code them. Constructors are automatically created when views are compiled into classes. The example below defines the parameters that must be injected instances from the dependency injection container in a view:
@model ....@using ......@inject MyOptions o
Injectable parameters are declared with directives at the top of the view with the @inject
keyword followed by the type to inject and the parameter where to inject it. Parameters defined in @inject
directives can be used throughout the whole view.
It is important to understand what kind of services are better injected in views instead of controllers. The answer is in the separation of concerns ...