Injection injection / constructor dependencies - working with "root" classes

I've been using a lot of dependency injection, test development, and unit testing lately and I'm starting to love it.

I use constructor dependency in classes so I can then inject mock dependencies for unit testing.

However, what is the best way to handle this when you really want objects in your production environment?

Are you using DependencyInjectionContainer.Get<MyClass>()

wherever you want to create a class? Or does it make sense to create an empty constructor for the class that resolves all dependencies through the DI container?

+3


source to share


1 answer


There is no need to have a default constructor.

In your production code, you usually should only have one call DependencyInjectionContainer.Get(someRootType)

in your application to get the root type (like a class HomeController

in MVC). Since all types are created using constructor injection, the container will be able to create the entire graph of related objects for you. Therefore, from a production point of view, it is not necessary to have more than one designer.



Since in your unit tests you usually need to inject all mocks, your tests will not use the default constructor. On the other hand, letting each test call to the constructor of the directly tested class will soon make the code difficult to maintain, as you have to change all tests when the constructor changes. Instead, centralize this logic with a factory method in your test class. This factory method can have several overloads to make it easier for tests to create a testable class.

+2


source







All Articles