Constructor Injection

Constructor Injection: Definition and When to Use It

Dependency Injection DI Wednesday, May 21, 2014

Dependency injection is a term that has been mainstream for a while now and, even if you haven't used it yet, certainly you saw it on a blog post somewhere. As proper definition of dependency injection states that the dependencies are given to the instance and so, in the constructor injection case, they are enforced by the constructor such as in the following example:

public class HomeController : Controller
    private readonly IContactService contactService;

    public HomeController(IContactService contactService)
        this.contactService = contactService;

    public ActionResult Index()
        return View();

This is the most common pattern used to implement dependency injection and we should try to use it as much as we can.

Why? Because in programming, the longer it takes for us to get feedback in the development life-cycle, the more costly it is to fix whatever need to be fixed. If your code has a dependency that is not being injected, your project will not compile. That's the fastest kind of feedback I can think of.

When not to use it?

If the dependency is optional and you have a good local default, when you have cyclic dependencies between classes, when the dependency is not available in the constructor or when the dependency supplied can vary with each method call.

You might also be tempted to go with property injection if you constructor becomes too polluted with many interfaces but, in that case, it may be time to use the facade pattern to reduce the amount of direct dependencies and complexity in your class has and allow potential code re-use.

Remember that for this to work, you need to setup a IoC container in your application and register the dependencies.