How would you inject a worker service in a controller class and perhaps a repository in a worker service? The most obvious way is by letting controllers and services create a fresh new instance of the dependent objects. This route, however, creates a tight dependency between objects that potentially hinders extensibility and testability. For this reason, many suggest inversion of control and IoC containers.

While there’s nothing to say about the effectiveness of this approach which is also clean and nifty, I question its wide applicability. Do you really need it all the time? Or are you just applying it victim of some form of geekiness? I now prefer having far simpler code that can evolve to tool-based inversion of control in a few clicks.

public class HomeController : Controller
{
   private readonly IHomeService _workerService;
   public HomeController() : this(new HomeService())
   {
   }
   public HomeController(IHomeService service)
   {
      _workerService = service;
   }
   ...
}

When the default constructor is used to instantiate a controller, the worker service member points to a freshly created instance of a default worker service class. A second constructor is available to manually inject any instance you like, at least for testability reasons. Likewise, you do the same for injecting the repository dependency into the worker service.
ASP.NET MVC, however, always uses the default constructor for each controller class, unless you gain control of the controller factory.

To jump to tool-based inversion of control, you just add IoC initialization and configuration. And a controller factory.

Categories

2 responses to “Poor man’s dependency injection”

  1. dotnetchris Avatar

    Very clear and succinct post describing Poor Man’s DI.

  2. […] of IContext  from the container in the constructor. There are of course better ways (i.e. poor man dependency injection or adding a factory to resolve pipeline processors), but for demonstrating I think it’s […]

Leave a comment

Upsidedown is a WordPress theme design that brings blog posts rising above inverted header and footer components.