Most dependency injection frameworks support some kind of object initialization through parameterized constructors. The question is whether or not it’s a good idea to use that feature of DI frameworks.

Consider the following code:

When we use a DI container such as Unity to instantiate a Worker object, we must write some specialized code to pass in the constructor parameter (payLoad in our example). The problem I see with this is that since parameterized constructors can’t be mandated through interface IWorker, the code is only guaranteed to work with the default implementation of IWorker if one is provided. That’s pretty ugly, and pretty much defeats the purpose of using a DI framework. One of the key benefits of using a DI framework is that a new “implementation” can be “injected” into code at any time by only making subtle changes to the configuration.

In most cases the code above should be refactored as below:

The above code is not only more concise, but is also more portable. In the event when payLoad needs to be used by more than one Worker method, we can create an explicit Initialize method to initialize the object. The code can be refactored as follows:

There are some very specialized instances when parameterized constructors need to be used in conjunction with DI frameworks, but those should be exceptions and must be used sparingly with deliberate intent.

Post a Comment

2 Comments on "Dependency Frameworks and Parameterized Constructors"

Sort by:   newest | oldest | most voted

Why you say “those should be exceptions and must be used sparingly”?