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?