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:

Get hands-on with 1200+ tech skills courses.