Question

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

I am using constructor dependency in classes, so that I can then inject mock dependencies for unit-testing.

However, what are the best way to deal with it, when you actually want the objects in the production environment?

Do you use DependencyInjectionContainer.Get<MyClass>() everywhere you want to create the class? Or does it make more sense to create a blank constructor for the class, which resolves all the dependencies via the DI container?

Was it helpful?

Solution

There's no need to have a default constructor.

In your production code you would typically have just a single call to DependencyInjectionContainer.Get(someRootType) in your application to get a root type (for instance a HomeController class in MVC). Since all types are created using constructor injection, the container will be able to create the whole graph of related objects for you. So from a production perspective there is no need to have more than one constructor.

Since in your unit tests you would typically want to inject all the mock objects, your tests won't use the default constructor either. On the other hand, letting each test call the constructor of the class under test directly would soon result in code that gets hard to maintain, since you will have to change all tests when the constructor changes. Instead, centralize that logic to a factory method within the test class. This factory method can have multiple overloads to make it easy for the tests to create the class under test.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top