CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Jeremy D. Miller -- The Shade Tree Developer

Under the hood and working with .Net, TDD, Software Design, and Agile Stuff

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



Comments

Paul's Imaginary Friend said:

Jeremy has a good, "article length" post covering the salient points of Dependency Injection using...
# October 7, 2005 3:47 AM

Paul's Imaginary Friend said:

Jeremy has a good, "article length" post covering the salient points of Dependency Injection using...
# October 7, 2005 8:39 AM

Michael said:

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.
# October 7, 2005 9:45 AM

Jeremy D. Miller said:

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.
# October 9, 2005 9:53 PM

Jeremy D. Miller -- The Shade Tree Developer said:

A fairly common topic with TDD practitioners, both newbie and experienced, is how the heck to unit test...
# October 12, 2005 3:04 PM

Jeremy D. Miller -- The Shade Tree Developer said:

StructureMap is an open source tool I’ve written for Dependency Injection support in .Net.  This...
# November 18, 2005 9:40 AM

K. Scott Allen said:

Richard tilted his head to watch the waves push flotsam against the boat hull below. Up and down, the...
# November 22, 2005 12:29 AM

Murat Uysal said:

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
# November 25, 2005 12:59 AM

Jeremy D. Miller -- The Shade Tree Developer said:

A friend of mine was asking me a while back about ways to apply the Model View Presenter (the “Humble...
# February 1, 2006 11:18 PM

Jeremy D. Miller -- The Shade Tree Developer said:

Author: <a href="blogs/jeremy.miller/">Jeremy D. Miller</a><br />A friend of mine was asking me a while back about ways to apply the Model View Presenter (the “Humble Dialog Box”) pattern to ASP.Net development to promote easier unit testing of the user interface layer. Two weeks and a major case of writer’s block later, I finally finished the post. I wrote a blog post last spring describing the usage of MVP (“The Humble Dialog Box”) with WinForms clients, but web development in general and ASP.Net in specific comes with a different set of challenges.
# February 2, 2006 7:11 PM

Jeremy D. Miller -- The Shade Tree Developer said:

This is a follow up to my post on the Model View Presenter pattern with ASP.Net to address or clarify...
# February 16, 2006 1:18 AM

Jeremy D. Miller -- The Shade Tree Developer said:

Author: <a href="blogs/jeremy.miller">Jeremy D. Miller</a><br />Carlton commented that the Presenter class looks a lot like the Gang of Four "Mediator" pattern. He's absolutely right. Something to keep in mind when learning to apply design patterns is that a class or group of classes can easily be an instance of more than one pattern. In this case "Presenter" or "Controller" is just a more specific name for a class within a larger structural pattern.
# February 16, 2006 9:22 AM

Jeremy D. Miller -- The Shade Tree Developer said:

This past Saturday was the Austin Code Camp.  I had a great time and the general consensus was that...
# March 6, 2006 8:32 AM

Haacked said:

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).
# March 7, 2006 3:02 AM

Jeremy D. Miller -- The Shade Tree Developer said:

Laws of TDD is probably something that should be written by someone with more authority in the community,...
# March 9, 2006 9:59 AM

Jeremy D. Miller -- The Shade Tree Developer said:

Author: <a href="blogs/jeremy.miller">Jeremy D. Miller</a><br />Laws of TDD is probably something that should be written by someone with more authority in the community, but I've got a blog and I thought of it first, so here goes. I'll expound on each of these at some point in the misty future, but just for fun here is Jeremy's Laws of Test Driven Development (I'm certainly not claiming any kind of originality here. Some of these rules predate TDD anyway).
# March 9, 2006 10:18 AM

David Hayden [MVP C#] said:

Jason Haley points to a really nice introduction to using NHibernate with ASP.NET, called NHibernate...
# March 12, 2006 10:39 AM

Jeremy D. Miller -- The Shade Tree Developer said:

Laws of TDD is probably something that should be written by someone with more authority in the community, but I've got a blog and I thought of it first, so here goes.  I'll expound on each of these at some point in the misty future, but just for fun here
# March 19, 2006 7:16 PM

Raymond Lewallen [MVP] said:

So I’m working in a maintenance release right now.  Very little
added functionality.  My current...
# May 1, 2006 11:02 PM

Jeremy D. Miller -- The Shade Tree Developer said:

The slide deck and sample code from my StructureMap talk last night is available from the ADNUG downloads...
# July 11, 2006 10:52 AM

Jeremy D. Miller -- The Shade Tree Developer said:

Between being extremely short handed at work, tech' reviewing a new book, a
possible book proposal...
# August 7, 2006 4:51 PM

cruizer said:

Looks like I can only include one attachment per blog post, so I was only able to put the presentation
# August 16, 2006 5:11 PM

Jeremy D. Miller -- The Shade Tree Developer said:

Between being extremely short handed at work, tech' reviewing a new book, a possible book proposal

# September 1, 2006 2:33 PM

Slade Stewart said:

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.

# September 27, 2006 11:22 AM

Jeremy D. Miller -- The Shade Tree Developer said:

It took long enough, and I've had a pretty good stream of people asking for this, so here it is:

# April 2, 2007 10:28 AM

mcgurk said:

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<int> as a parameter, your callers are restricted to that specific collection.  However, if you take an IEnumerable<int>, 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<int>, you callers can treat it as a List<int>, an ICollection<int>, and IEnumerable<int> 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...

# April 3, 2007 8:35 AM

Jeremy D. Miller said:

Mcgurk,

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

# April 3, 2007 10:25 AM

Ian Goodsell - Dev Emporium said:

Jeremy D. Miller has some really good articles on unit testing, design and TDD. Here are some gems: ...

# April 19, 2007 4:04 PM

Afif said:

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?

# May 18, 2007 1:46 AM

Jeremy D. Miller said:

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.

# May 18, 2007 8:22 PM

58bits - Tech - Application Block Software Factory - Sample App said:

Pingback from  58bits - Tech - Application Block Software Factory - Sample App

# July 3, 2007 5:07 PM

Chad Myers' Blog said:

Starting a new set of projects, what to do?

# October 29, 2007 3:58 PM

Jeremy D. Miller -- The Shade Tree Developer said:

Author: Jeremy D. Miller A friend of mine was asking me a while back about ways to apply the Model View Presenter (the “Humble Dialog Box”) pattern to ASP.Net development to promote easier unit testing of the user interface layer. Two weeks and a major

# November 8, 2007 7:48 AM

oil portraits said:

Thanks for sharing this informati