ASP.NET Core – Is Using [FromServices] Attribute Bad Practice?

asp.net-mvccdependency-injection

I have a Controller in ASP Core MVC. I'm trying to trim down the dependency injected services in the constructor so I can start building unit tests more easily. However, I have some services being injected that are only used in one or two controller actions. For example, I inject ILocationService because in a couple of my actions, I need to lookup a country Id number and get a ISO Alpha-2 country code using a database (eg mapping ID number 1 to "CA", mapping 2 to "US", etc.)

Asp Core supports the [FromServices] attribute, so I have the option to inject ILocationService directly into two of my actions instead of injecting them in the controller constructor. The advantage for this is I don't need to always mock/inject ILocationService into my controller from every unit test and its more clear when writing unit tests which services each function depends on.

The obvious disadvantage is now its not completely obvious and clear what services my controller depends on since they are not all grouped in the constructor.

Is using [FromServices] bad practice or a strong indication of code smell?

Best Answer

This isn't a code smell or bad design at all. In fact, this is precisely why the [FromServices] attribute was created:

Action Injection with FromServices

Sometimes you don't need a service for more than one action within your controller. In this case, it may make sense to inject the service as a parameter to the action method. This is done by marking the parameter with the attribute [FromServices]...

Source: Dependency injection into controllers in ASP.NET Core (emphasis, mine).