📜 ⬆️ ⬇️

Love or marriage of convenience with Dependency Injection?

In my article I want to consider an example of the wrong use of the Dependency Injection principle and try to find motivation for other developers of the team (and maybe someone else still fit) to write new code better, as well as as they run through working activities with someone else’s code, written in an illiterate way, do refactoring.

So, the essence of the problem. On the project, we use OData WebApi and all controllers are inherited from the base class, using the GetService method from the base class, which pulls dependencies through the ApiControllerScopeContextMediator static class.

public abstract class ODataControllerBase : ODataController { protected T GetService<T>() { return ApiControllerScopeContextMediator.GetService<T>(this); } } internal static class ApiControllerScopeContextMediator { internal static T GetService<T>(ApiController controller) { return (T) controller.Configuration.DependencyResolver.GetService(typeof (T)); } } 

And in Global.asax we configure dependency pulling for OData through StructureMap:
')
  GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container); 

In all actions at the controllers, the GetService method is commonly used, for example, here:

 public class DisconnectedAppsController : ODataControllerBase { public IHttpActionResult Get() { var query = GetService<IQuery<IQueryable<DisconnectedAppDomain>, DisconnectedAppFilter>>(); } } 

But why? After all, one could simply use constructor injection:

 public DisconnectedAppsController(IQuery<IQueryable<DisconnectedAppDomain>, DisconnectedAppFilter> query){ _query = query; } 

So all the same: “Tahiti, Tahiti” (Constructor Injection) or “they feed us well here too” (GetService)?

What problems with this code I see:


What arguments "against" I happened to hear:


A couple of years ago I read the book by Mark Siman “Dependency Injection” . I sit and think, so what do I have with DI: love or a marriage of convenience?

Used materials:

Mark Seeman "Dependency Injection"
Mark Seeman's blog
Microsoft MVC6 github open source project
SOLID wiki page
YAGNI wiki page
KISS wiki page

Source: https://habr.com/ru/post/271853/


All Articles