The Dependency Injection Pattern – What is it and why do I care?

A couple of weeks ago I wrote about using the Inversion of Control (IoC) principle to create classes that are easier to unit test.  One major thing I left out of that post was using the Dependency Injection pattern to loosely couple classes from their dependencies.  In a nutshell, dependency injection just means that a given class or system is no longer responsible for instantiating their own dependencies.  In this case “Inversion of Control” refers to moving the responsibility for locating and attaching dependency objects to another class or a DI tool.  That might not sound that terribly profound, but it opens the door for a lot of interesting scenarios.


 


While there’s a fair amount of unnecessary buzz and hype about the concept, I’ve found Dependency Injection to be very advantageous for doing Test Driven Development without pulling your hair out.  If you’ve seen articles or blog posts about Dependency Injection but don’t quite internalize the value of DI yet, here are the facts as I see them:


 



  1. Dependency Injection is an important pattern for creating classes that are easier to unit test in isolation

  2. Promotes loose coupling between classes and subsystems

  3. Adds potential flexibility to a codebase for future changes

  4. Can enable better code reuse

  5. The implementation is simple and does *not* require a fancy DI tool

 


The PicoContainer team even has silly tee shirts printed up that say “I expected a paradigm shift, but all I got was a lousy constructor function.”  DI is certainly a case where a minimum of effort supplies quite a bit of benefit.  Don’t blow it off just because it seems trivial. 


 


There are tools out there that do Dependency Injection in .Net.  I use my own tool called StructureMap in my development, but I’m going to focus on only the concept of DI in this post.


 


Example Problem


 


My first experience with conscious usage of DI was a WinForms client communicating with the backend via web services that was built with the Model View Presenter (“Humble Dialog Box”) architecture for easier unit testing.  Most screens in the client end up with something like this set of classes:



  • Model – Whatever business object/DataSet/chunk of data is being displayed or edited

  • View – A WinForms UserControl class.  Displays data to a user and captures user input and screen events (duh).

  • Service – A web service proxy class to send requests to the backend

  • Presenter – The controller class that coordinates all of the above.

 


The presenter class without Dependency Injection might look like this.


 


      public class Presenter


      {


            private View _view;


            private Model _model;


 


            public Presenter(){}


 


            public object CreateView(Model model)


            {


                  _model = model;


                  _view = new View();


                  _view.DisplayModel(model);


 


                  return _view;


            }


 


            public void Close()


            {


                  bool canClose = true;


                 


                  if (_view.IsDirty())


                  {


                        canClose = _view.CanCloseDirtyScreen();  


                  }


 


                  if (canClose)


                  {


                        _view.Close();


                  }


            }


 


            public void Save()


            {


                  Service service = new Service();


                  service.Persist(_model);


            }


      }


 


This code cannot be unit tested in isolation because it has a tight coupling to a concrete implementation of both the WinForms UserControl (View) and the proxy class to a web service (Service).  This code as is cannot function without both the User Interface and a web server running the backend.   The point of using the MVP is to isolate most of the user interface logic away from the WinForms and web service mechanics to enable effective unit testing, so we’re missing something here.  To unit test the presenter logic we’d like to replace the user interface and web service dependencies with a Mock object inside our test fixture classes.  In order to mock the view and service, we first need to use the Dependency Inversion Principle to make the Presenter class depend on an abstracted IView and IService interface instead of the concrete UserControl and WebProxy classes.  The next thing to do is to alter the Presenter class so that we can substitute at run time the mock objects instead of the concrete classes within the unit tests.  This is where Dependency Injection comes into play.


 


There are a couple of different flavors of Dependency Injection (via Martin Fowler + the Pico guys)



  1. Constructor Injection – Attach the dependencies through a constructor function at object creation

  2. Setter Injection – Attach the dependencies through setter properties

  3. Interface Injection – This is an odd duck.  I’ve never used it or seen this used.  I suspect its usage is driven by specific DI tools in the Java world.

  4. Service Locator – Use a well known class that knows how to retrieve and create dependencies.  Not technically DI, but this is what most DI/IoC container tools really do.

 


Constructor Injection


 


My preference is to use the “Constructor Injection” flavor of DI.  The mechanism here is pretty simple; just push the dependencies in through the constructor function. 


 


      public class Presenter


      {


            private IView _view;


            private Model _model;


            private IService _service;


 


            public Presenter(IView view, IService service)


            {


                  _view = view;


                  _service = service;


            }


 


            public object CreateView(Model model){…}


            public void Close(){…}


            public void Save(){…}


      }


 


      [TestFixture]


      public class PresenterTestFixture


      {


            private IMock _serviceMock;


            private IMock _viewMock;


            private Presenter _presenter;


 


            [SetUp]


            public void SetUp()


            {


                  // Create the dynamic mock classes for IService and IView


                  _serviceMock = new DynamicMock(typeof(IService));


                  _viewMock = new DynamicMock(typeof(IView));


 


                  // Create an instance of the Presenter class using the mock objects


                  _presenter = new Presenter(


                        (IView) _viewMock.MockInstance,


                        (IService) _serviceMock.MockInstance);


            }    


      }


 


One of the benefits of using Constructor Injection is that the constructor function now explicitly declares the dependencies of a class.  I also thing Constructor Injection makes it easier for other developers to use your class because it expresses a contract.  Give the class what it needs in its constructor function and it should be ready to function.  It’s usually a best practice to create a valid object in as few steps as possible for ease of use.  Using Constructor Injection also allows you to maintain more encapsulation by eliminating the need to expose getter and setter properties for dependencies like the IService interface that are immutable.


 


Exposing the dependencies in a constructor function is arguably a violation of encapsulation because now a client of Presenter would have to create instances of IView and IService first before calling the constructor function.  To get around this issue I usually suggest a compromise.  Create a second no argument constructor that builds the default instances for clients of Presenter to use.  The “full” constructor is usually commented as a testing constructor.  Some people think this pattern is evil redundancy, but it gets the job done.


 


            // Testing constructor


            public Presenter(IView view, IService service)


            {


                  _view = view;


                  _service = service;


            }


 


            // Default constructor


            public Presenter() : this(new View(), new Service()){}


 


Setter Injection


 


Setter injection is just creating a setter property to replace a dependency on a previously instantiated object.  I don’t like Setter Injection because it requires extra, hidden steps to prepare an object to execute.  I’ve been burned a couple times in the last year when I’ve inherited some code that depended on setters to set up dependencies.  That being said, Setter Injection does work and is often necessary when you’re dealing with existing code.  Michael Feathers recommends using Setter Injection as a dependency breaking technique for legacy code when a dependency is too difficult to expose through a constructor.


 


Here’s the Presenter class using Setter Injection.


 


      public class Presenter


      {


            private IView _view;


            private Model _model;


            private IService _service;


 


            public Presenter()


            {


                  _view = new View();


                  _service = new Service();


            }


 


            public IView View


            {


                  get { return _view; }


                  set { _view = value; }


            }


 


            public IService Service


            {


                  get { return _service; }


                  set { _service = value; }


            }


 


            public object CreateView(Model model){…}


            public void Close(){…}


            public void Save(){…}


      }


 


      [TestFixture]


      public class PresenterTestFixture


      {


            private IMock _serviceMock;


            private IMock _viewMock;


            private Presenter _presenter;


 


            [SetUp]


            public void SetUp()


            {


                  // Create the dynamic mock classes for IService and IView


                  _serviceMock = new DynamicMock(typeof(IService));


                  _viewMock = new DynamicMock(typeof(IView));


 


                  // Create an instance of the Presenter class


                  _presenter = new Presenter();


 


                  // Attach the Mock objects


                  _presenter.View = (IView) _viewMock.MockInstance;


                  _presenter.Service = (IService) _serviceMock.MockInstance;


            }


      }


 


Here’s a variation on Setter Injection I’ve seen other teams use.  In the getter of the property, just create the default instance of the dependency if it hasn’t been created.  I don’t like this approach because it hides the dependencies of a class.  I think this is creating “Mystery Meat” dependencies and brittle code.  In practice I thought that this made it difficult to retrofit unit tests into existing code.  Of course, retrofitting unit tests onto existing code is always hard so maybe that’s really not a drawback.


 


            // Always access the _view field through the Property


            public IView View


            {


                  get


                  {


                        if (_view == null)


                        {


                              _view = new View();


                        }


                       


                        return _view;


                  }


                  set { _view = value; }


            }


 


Service Locator


 


An alternative to using Dependency Injection is to use a Service Locator to fetch the dependency objects.  Using a Service Locator creates a level of indirection between a class and its dependencies.  Here’s a version of the Presenter class that gets its IView and IService dependencies by asking StructureMap’s ObjectFactory class for the default type and configuration of IView and IService.  While it is generally possible to use the Service Locator to return mock or stub objects inside test fixtures, I would still prefer to leave a testing constructor so the unit tests can be simpler.  I find that using a Service Locator within a unit test can be confusing because it’s not clear where the mock object is used.


 


      public class Presenter


      {


            private IView _view;


            private Model _model;


            private IService _service;


 


            public Presenter()


            {


                  // Call to StructureMap to fetch the default configurations of IView and IService


                  _view = (IView) StructureMap.ObjectFactory.GetInstance(typeof(IView));


                  _service = (IService) StructureMap.ObjectFactory.GetInstance(typeof(IService));


            }


            public object CreateView(Model model){…}


            public void Close(){…}


            public void Save(){…}


 


      }


 


I’ve seen several teams go their own way to create custom Service Locator’s, usually with a Singleton like this.


 


      public class ServiceFactory


      {


            private static IService _instance = new Service();


 


            private ServiceFactory(){}


 


            public static IService GetInstance()


            {


                  return _instance;


            }


 


            // Used to register mock or stub instances in place of


            // the concrete Service class


            public static void RegisterInstance(IService instance)


            {


                  _instance = instance;


            }


      }


 


I detest this pattern and I’ve been eliminating this from my team’s primary product.  There are just too many opportunities to screw up your tests by not having isolated unit tests.  It’s also unnecessary because there are existing tools specifically for this.


 


Good for More than Unit Testing


 


I’ve focused almost entirely on the value of Dependency Injection for unit testing and I’ve even bitterly referred to using DI as “Mock Driven Design.”  That’s not the whole story though.  One of original usages for Dependency Injection was to provide smoother migration paths away from legacy code.  One evolutionary approach to replacing legacy code is the “Strangler” approach.  Making sure that any new code that depends on undesirable legacy code uses Dependency Injection leaves an easier migration path to eliminate the legacy code later with all new code.


 


      public interface IDataService{}


 


      // Now


      public class ProxyToNastyLegacyDataService : IDataService{}


 


      // Later


      public class CleanNewCodeDataService : IDataService{}


 


      public class StranglerApplication


      {


            public StranglerApplication(IDataService dataService){}


      }


 


Another benefit of Dependency Injection is increasing the potential for reuse later.  Going back to the MVP architecture, what if you need to replace the heavy WinForms client with an ASP.NET system?  The View is obviously useless, and I think it’s probably silly to use a Web Service when a local class will do for the IService implementation.  We can potentially reuse the Presenter class; just inject a different implementation for both IView and IService.


 


      public class ASPNetView : System.Web.UI.UserControl, IView


      {


           


      }


 


      public class LocalService : IService


      {


           


      }


 


      public class WebClientMasterController


      {


            public void CreateView(Page page)


            {


                  ASPNetView view = (ASPNetView) page.Controls[0];


                  Model model = this.GetModel();


 


                  IService service = new LocalService();


 


                  // Presenter can work with a different concrete implementation of


                  // IView and IService


                  Presenter presenter = new Presenter(view, service);


                  presenter.CreateView(model);


            }


 


            public Model GetModel(){return new Model();}


      }


 


Using a Dependency Injection Tool


 


Using Dependency Injection potentially adds some overhead to using the classes that don’t create their own dependencies.  This is where one of the Dependency Injection tools can pay large dividends by handling this mechanical work and creating some indirection between clients and dependencies.  The next (and last) post in the whole Inversion of Control chain will look at using a Dependency Injection tool to “wire up” an application.


 


Links


About Jeremy Miller

Jeremy is the Chief Software Architect at Dovetail Software, the coolest ISV in Austin. Jeremy began his IT career writing "Shadow IT" applications to automate his engineering documentation, then wandered into software development because it looked like more fun. Jeremy is the author of the open source StructureMap tool for Dependency Injection with .Net, StoryTeller for supercharged acceptance testing in .Net, and one of the principal developers behind FubuMVC. Jeremy's thoughts on all things software can be found at The Shade Tree Developer at http://codebetter.com/jeremymiller.
This entry was posted in Design Patterns, Test Driven Development. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Chase

    One of the better articles I’ve read about DI. Great job.

  • Tommyrojo

    Thank you, excellent example. Very clear and easy to follow.

  • Martinez

    Terrible. Why do you post anything and not bother to format it correctly?

  • a true professional

    nice code format. . .

  • Rasaq Otunba

    Over 6 years later, some of us are still benefiting from this brilliant work. Thanks, Jeremy! 

  • http://www.key-logger.ws Lokesh Ruhela
  • http://revizyonileorganizematbaacilikbrnckvvtmllttrhaberi.bloggum.com revizyon ile organize matbaacılık brnckvvtmllttrhaberi

    thank you

  • http://www.portraitkingdom.com oil portraits

    Thanks for sharing this information. I can still my favorite professor way back in college whose favorite design technique is Construction Injection. May I know what sets the difference between Setter Injection and Construction Injection?

  • http://codebetter.com/blogs/jeremy.miller Jeremy D. Miller

    Afif,

    I don’t agree with you at all ;-)

    You’ve mistated some little things. You do not have to use the attributes at all if you don’t want to. In some very common cases the attributes can take the xml configuration down to near zero, and that’s cool in my book. If you don’t want to use attributes at all, everything can be done via Xml, assuming you have a high tolerance for coding in Xml. 2.0 did make the Xml configuration quite a bit tighter with less duplication.

    As of 2.0, you can wire up dependencies in code with a Fluent interface as well. Can Spring.Net do that? Didn’t think so.

    Honestly, I don’t like Spring.Net’s approach to IoC at all, but I’m too biased to make a judgement. StructureMap (and Castle Windsor) does auto wiring vastly better than Spring.Net because it’s type safe. No wiring stuff together by string values. Use Type’s first.

  • Afif

    Jeremy,

    I noticed Structuremap requires metadata attributes to identify classes and methods as pluggable / interfaces / constructors / factory… Then you have to write the config files to link everything together, but you can only inject classes that you have written using structuremap attributes…

    Spring is much better – all configuration is external in the config and will work with any class / library written by anyone.

    Structuremap probably is faster, but not as flexible as Spring.

    How far do you agree?

  • http://codebetter.com/blogs/jeremy.miller jmiller

    Mcgurk,

    A pattern is just that, a solution that reoccurs. It’s just something you do.

  • mcgurk

    Holy crap. Can we please not go shit-crazy with jargon? I come here because I’ve never heard of “Dependency Injection”; I thought it was some wicked cool new pattern. Come to find out that this “Dependency Injection” isn’t a fucken pattern at all–its standard best practices when it comes to method signatures.
    Your methods should take base objects/interfaces as input and return high-level objects.
    If your method takes a List as a parameter, your callers are restricted to that specific collection. However, if you take an IEnumerable, your callers can choose to use one of the many implementations of the interface (I count 15 in mscorlib alone).
    If you return an IEnumerable, your callers can only enumerate through the result set. But if you return a List
    , you callers can treat it as a List, an ICollection, and IEnumerable or just as an IEnumerable.
    Its amazing how brilliant I am; I’ve been doing this ever since I read CLR Via C#. I had no idea I was implementing the Dependency Injection pattern. Lurl. I wonder what other patterns I’m implementing…

  • http://www.teclallc.com Slade Stewart

    I haven’t yet finished reading your post, but I wanted to let you know that a) I like it so far, and b) you have provided me with my new motto: “Don’t blow it off just because it seems trivial”. That seems to apply to most of the most effective concepts in software development and with how they are received in general.

  • Richard Corfield

    I use the Setter Injection pattern, often with “lazy instantiation” in a situation where I know at design time the one implementation that I need, but know also that for testing or in the future there may be others. Where I know at design time that there are multiple implementations I use Inversion of Control and wire them up at a higher level – still with Setter Injection.

    I have debated with other developers a lot about constructors and whether you should leave them spartan or put all your dependencies in them. If you leve them spartan you have a class in an invalid state. If you place all dependencies then you have something that, in the past at least, I’ve thought of as being harder to extend. What happens when you add a new dependency?

    With Setter Injection you provide a default implementation of that new dependency (or null for “don’t use this” perhaps) and old code still works. With the dependencies in the constructor you have to provide an overload to allow old code to work.

    I suppose both mechanisms can work and it comes down to style. All in the constructor can give you more compact code where you create something and assign it in one, but this can become messy with many indented nested constructions and is a nightmare to debug on current Microsoft debuggers at least. (You can’t get at the intermediate values and stepping in is hard).

    What’s nicer?

    Foo myFoo = new Foo(
    “Hello”,
    12,
    “This is a Foo”,
    new Bar
    (
    96,
    myDBConnection
    )
    );

    or

    Bar barProvider = new Bar();
    barProvider.PoolSize = 96;
    barProvider.Database = myDBConnection;

    Foo theFoo = new Foo();
    foo.ID = “Hello”;
    foo.Name = “This is a Foo”;
    foo.MagicNumber = 12;
    foo.BarProvider = barProvider;

  • http://haacked.com/ Haacked

    Jeremy, I know you wrote this a looong time ago, but I was reading up on Dependency Injection and noticed something I thought I should point out.

    You mentioned that in your presenter, you sometimes use an empty constructor to set up default views and models.

    > public Presenter() : this(new View(), new Service()){}

    The problem with this is that this Presenter now has a dependency on concrete instances of the IView and IService, which was kind of the point of using IOC and DI.

    This would be a problem in the example of re-use within ASP.NET you mentioned.

    > We can potentially reuse the Presenter class;
    > just inject a different implementation for both
    > IView and IService.

    The problem is that the Presenter class has a dependency on a WinForm View and Service, which you’ll need to include with your ASP.NET application.

    Of course, I’m being nitpicky and I apologize. In the real world, I would go with your approach and if I really DID need to use the presenter in ASP.NET, I’d probably change it.

    It’s that balance between potential re-use and premature generalization (http://haacked.com/archive/2005/09/19/10231.aspx).

  • Murat Uysal

    I have been reading your post and finding them really informative and to the point. Thanks for all the great effort in sharing your experince.

    I have one question here. I have been using the what you call “Setter Injection” for breaking the dependency of domain objects to database. I am using the domain model pattern with the mapper pattern. So far I have been thinking about this dependency breaking technique as abstracting the mapper by Dependency Inversion principle and setting the dependency property with a stub in order to do unit testing. And I was thinking it is an example of “Strategy Pattern”. I know the important thing is to break the dependency but as you mentioned at one of your old posts it is also important to use the right pattern name at the right place.

    Thanks for all the great posts again,

    Murat

  • Jeremy D. Miller

    Michael,

    All I meant is that you might use a service locator to rig up a mock object or a stub in one test fixture and forget to clean up the static member. That static state can leak into another testfixture. You’ll notice that you start getting nasty behavior like a test passing when it runs by itself but failing when it runs with the rest of the test suite.

    The other thing is that using a service locator inside of a unit test makes it a little bit harder to see where that particular dependency comes into play.

    Thanks for the kind words.

  • Michael

    Can you expand on “There are just too many opportunities to screw up your tests by not having isolated unit tests” in reference to a custom Service Locator? I can obviously infer a bit on my own, but perhaps just a brief blurb in your own words to hear what your experiences have been when using that pattern in practice?

    Otherwise, great post as usual. The focus on patterns lately is awesome. Despite the fact that absolutely everyone is covering it, your explanations and examples are always well presented, real-world, and usable, which is a nice change of pace from the academia found elsewhere.