Dependency injection: what do you lose when creating specific classes in the constructor without parameters

Generally speaking, my dependencies are abstracted to interfaces, but I will use only one specific implementation during use without testing. For example, I had to write FooService :

 public class FooService : IFooService { private readonly IBarDependency _barDependency; public FooService(IBarDependency barDependency) { this._barDependency = barDependency; } public FooService() : this (new BarDependency()) { // nothing to do here } . . . // code goes here } 

Now purists tend to suffocate in horror because I created a specific class in a parameterless constructor. I in the past shrugged because I know that the only time I will not use a particular class is when I test units of measure and mocking dependencies.

While it connects the FooService class to the FooService class, it is not a hard link; these classes and interfaces also exist in the same assembly, so it doesn't seem to me that I'm losing a lot of space here or drawing myself into a corner. I can still easily test the FooService class without getting unmanaged code, just using a constructor that allows me to pass in mocking interfaces.

So the question is: what is really at stake? What am I losing with a template worth adding an IoC container?

+7
c # dependency-injection interface
source share
3 answers

Lifecycle management, for example. Perhaps you are using BarDependency in all of your code and only want one instance to be alive. You cannot do this if each user creates their own instances.

You also need to find all the uses of new BarDependency() if you want to replace it with new NewBarDependency() .

The container fixes both problems for you, since you configure the instance and the life cycle of objects in one way, namely, where you configure your container.

+6
source share

It depends, but if FooService needs to access another developer, the dependency on BarDependency will be mostly hidden. In my opinion, not only bullying and testing is the reason for using dependency injection, but also a clear indication of what certification classes use and what they should work for properly. And maybe I'm on a big purist, but when such a template is in order, then it easily moves on and ends with a completely dense and tough managed code.

+2
source share

What you lose without dependency injection is the ability to centralize all aspects of dependency management. Visualizing the dependency graph and managing the life cycles of your objects is easier if you have all the information in one place, and not scattered throughout the code.

A concrete example would be if you want to replace the standard IBarDependency implementation used in some, but not all classes. The discussion of which ones to replace is much simpler if all the dependencies are related to each other in one file or group of files.

+1
source share

All Articles