Dependency Injection for Loose Coupling

This article describes the use of Dependency Injection, or Inversion-of-Control, to promote loose coupling and convenient unit testing.

Introduction

In designing an object-oriented application, a major tenet of design is "loose coupling". Loosely, not meant for the pun, "loose coupling" means that objects should only have as many dependencies as is needed to do their job - and the dependencies should be few. Furthermore, an object's dependencies should be on interfaces and not on "concrete" objects, when possible. (A concrete object is any object created with the keyword new.) Loose coupling promotes greater reusability, easier maintainability, and allows you to easily provide "mock" objects in place of expensive services, such as a socket-communicator.

"Dependency Injection" (DI), also more cryptically known as "Inversion of Control" (IoC), can be used as a technique for encouraging this loose coupling. There are two primary approaches to implementing DI: constructor injection and setter injection. Obviously, at some point, something must be responsible for creating the concrete objects that will be injected into another object. The injector can be a parent object, which I'll call the "DI controller", or can be externalized and handled by a "DI container" framework. What follows is a brief overview of the various approaches for using dependency injection techniques.

Constructor Injection

Constructor Injection is the DI technique of passing an object's dependencies to its constructor. The below example includes a class, Customer, that exposes a method for retrieving every sales-order that the customer made on a particular date. Consequently, the Customer class needs a data-access object for communicating with the database. Assume, an OrderDao ("order data-access object") exists which implements the interface IOrderDao. One way that a Customer object can get this dependency is by executing the following within the: IOrderDao orderDao = new OrderDao();. The primary disadvantage of this is two-fold:

the benefit of having the interface in the first place has been negated since the concrete instance was created locally, and

OrderDao cannot easily be replaced by a mock object for testing purposes. (Mock objects will be discussed shortly.)

In the example, note that the constructor accepts an interface; it does not accept a concrete object. Also, note that an exception is thrown if the orderDao parameter is null. This emphasizes the importance of receiving a valid dependency. Constructor Injection is, in my opinion, the preferred mechanism for giving an object its dependencies. It is clear to the developer invoking the object which dependencies need to be given to the Customer object for proper execution. But consider the following example... Suppose you have a class with ten methods that have no dependencies, but you're adding a new method that does have a dependency on IOrderDao. You could change the constructor to use Constructor Injection, but this may force you to change constructor calls all over the place. Alternatively, you could just add a new constructor that takes the dependency, but then how does a developer easily know when to use one constructor over the other. Finally, if the dependency is very expensive to create, why should it be created and passed to the constructor when it may only be used rarely? "Setter Injection" is another DI technique that can be used in situations such as this.

Setter Injection

Setter Injection does not force dependencies to be passed to the constructor. Instead, the dependencies are set onto public properties exposed by the object in need. As implied previously, the primary motivators for doing this include:

supporting dependency injection without having to modify the constructor of a legacy class, and

allowing expensive resources or services to be created as late as possible and only when needed.

The code below modifies the Constructor Injection example to use Setter Injection instead:

publicclass Customer {
public Customer() {}
public IOrderDao OrderDao {
set { orderDao = value; }
get {
if (orderDao == null)
thrownew MemberAccessException("orderDao" +
" has not been initialized");
return orderDao;
}
}
public IList GetOrdersPlacedOn(DateTime date) {
//... code that uses the OrderDao public
//... property to get orders from the datasource ...
}
// Should not be called directly;
// use the public property instead
private IOrderDao orderDao;
}

In the above example, the constructor accepts no arguments. Instead, the invoking object is responsible for setting the IOrderDao dependency before the method GetOrdersPlacedOn is called. With Constructor Injection, an exception is thrown if the dependency is not set immediately, i.e., upon creation. With Setter Injection, an exception isn't thrown until a method actually attempts to use the dependency. Make note of the fact that GetOrdersPlacedOn uses the public OrderDao property; it does not call the private orderDao directly. This is so that the getter method has an opportunity to validate if the dependency has yet been initialized.

Setter Injection should be used sparingly in place of Constructor Injection, because it:

does not make it clear to the developer which dependencies are needed when, at least until a "has not been initialized" exception is thrown, and

makes it a bit more difficult to track down where the exception came from and why it got thrown. With this said, Setter Injection can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.

The Injectors

The next logical question is, what actually creates the dependencies that are to be injected into "injectees"? There are two appropriate places for adding creation logic: controllers and containers.

DI Controllers

The "DI controller" approach is the simpler to understand and implement. In a properly tiered architecture, an application has distinct layers for handling logic. The simplest layering usually consists of a data-layer for talking to the database, a presentation-layer for displaying the UI, and a domain-logic layer for performing business logic. A "controller" layer always exists, even if not well defined, for coordinating UI events to the domain and data layers, and vice versa. For example, in ASP.NET, the code-behind page acts as a rudimentary controller layer. More formalized controller-layer approaches exist: Struts and Spring for Java; Front Controller and Spring .NET for .NET. All of these approaches follow some form of variant of the Model-View-Controller pattern. Regardless of what you use as your controller, the controller is an appropriate location for performing Dependency Injection "wiring". This is where concrete objects are created and injected as dependencies. What follows are two examples of DI performed by a controller. The first is an illustrative example of "production code" - code that you'd end up deploying. The second is an example of "test code" - code that's used to test the application, but is not deployed and does not have the need to have a live database.

One of the major benefits of using a DI-controller to inject dependencies is that it's straightforward and easy to point to where the creation is occurring. The drawback to using DI-controllers is that the dependencies are still hard-coded somewhere; albeit, they're hard-coded in a location that is often subject to frequent changes anyway. Another drawback is that now the DI-controllers themselves can't be easily unit-tested with mock objects. (Granted, a powerful tool such as TypeMock can do just about anything when it comes to injecting mock objects. But a tool such as TypeMock should be used only when absolutely necessary as it can lead to habits of not programming-to-interface. In fact, I'd recommend only considering the use of it on very difficult to test, legacy applications.)

In ASP.NET, I prefer to use the Model-View-Presenter (MVP) pattern, and have the ASP.NET code-behind page create dependencies and inject them to the presenter via Construction Injection. Additionally, I use UserControls as the View part of the pattern, so the ASP.NET code-behind acts purely as an MVP "dependency initializer" between the UserControls (View) and their presenters.

Another option to implementing constructor or setter DI is the use of an application container...

DI Containers

Inversion-of-Control/Dependency-Injection "containers" can be used to watch an application and inject dependencies whenever a particular event occurs. For example, whenever a Customer instance is created, it automatically gets injected with its needed dependencies. It's a strange concept at first, but can be useful for managing large applications with many service dependencies. Different container providers each have their own mechanism for managing dependency injection settings.

The ASPX code-behind simply exposes a public property called DaoFactory that "catches" the dependency whenever the page gets called. See Spring .NET's website for more details and more examples. For Java developers, be sure to check out Spring's website.

Many other containers exist, some of which don't require much XML management at all (for those of you that cringe at the sight of a 500 line XML file). For Java developers, take a look at Container Comparison for a good comparison of options. For .NET developers, the decision is simpler as fewer options exist. (Is that a good thing?) See Open Source Inversion of Control Containers in C# for some open-source options.

Unit Testing with Injected Mock Objects

The greatest benefits that I've experienced using DI are cleaner unit testing and greater portability. Portability is a given as most of the dependencies are on interfaces. But let's look at how DI can benefit unit testing as well. It is often the case that developers write unit tests against a live database. This is all well and fine, but it quickly brings the speed of a suite of unit tests to a crawl. To keep unit testing from becoming a drag, it needs to be easy to turn off slow unit tests that actually hit the database while still testing the business logic that depends on data access. Mock objects are perfect for doing just this. A mock object simulates the responses of an actual object, acting as if it's using a real resource. They're great for mocking access to a database, mocking calls to IO, mocking calls to a web service, etc.

The below code shows a mock data-access implementation of the IOrderDao interface used throughout the article:

This trivial, mock data-access object implements IOrderDao, and can therefore be passed to any object that's dependent on IOrderDao via Constructor or Setter injection. Now all your business logic can be tested without actually hitting the database. In my own test suite, I usually have a section that contains "real" database tests, and then pass mock database-access objects for testing my domain objects.

Great article - it certainly explains an often complex issue in a nice straight forward manner. I have a question though; how does dependency injection work with ORM (in my case NHibernate)? If you use a DI container (Castle Windsor for example) and wire up the domain objects for either constructor or setter injection will NHibernate respect these wirings?

For example, if you've persisted an object and have then at some future time used the ORM to load the object will the dependencies be re-injected into the loaded objects?

In my own work, I don't use Container DI to inject dependencies into the business objects themselves. Alternatively, I inject them into the controller/presenter layer of an MVP separation of logic. In almost every case, I try to keep my business objects with as little dependency on services as possible and stick strictly to domain rules. But obviously, there are situations in which business objects need service dependencies, such as to an email utility. In this case, I use Container DI to give the controller the email utility and then manually pass the email utility to the business object from the controller/service layer. Since it happens rarely - in my current app, anyway - this setup doesn't create a lot of overhead and still provides a high level of service-independent testability.

I mostly use constructor injection, but I remember using setter injection once when I had a circular dependency...so I just thought I'd add that it's useful when you have circular dependencies (through interfaces of course, otherwise you'd want to make them into the same class!)

Great article! I've been wondering about DI for some time now; it's nice to finally have an idea of what it means.

Do you know what type(s) of dependency injection the new Composite UI Application Block (CAB) uses? I've heard that CAB uses DI to promote loose coupling, but haven't yet had a chance to investigate further.

I have never liked 'Setter Injection' as I find it confuses other developers who use my frameworks, so I tend to use constructor injection as you describe it in your article.

However, I also often require an interface to be passed as a method argument -- using your naming convention I guess we'll call this 'Method Injection'.

E.g. your code would look like:

public IList GetOrdersPlacedOn(DateTime date, IOrderDao OrderDao) {
... code that uses the OrderDao parameter to get orders from the datasource ...
}

This has the benefits of the Setter injection technique but does require that the caller DI Controler or DI Container handle the dependency lifetime -- this can be a good thing for expensive resources that can be disposed immediately by the controller.
It is generally easier to understand by third parties than setter injection.

I would agree that "Setter Injection" can often times fall into the realm of patternitus. The only time I've found it truly usefulis for page injection from Spring .NET. Otherwise, I don't see much use for it in non-container scenarios.

How do you see the difference between low coupling and loose coupling? I believe that there is a difference.

Here are my thoughts:

Low Coupling is when you have objects coupled, like in the Point of Sale domain, you might have a Register create a Payment and then pass the Payment to the Sale object, in this example, you have higher coupling on the Register, because the Register now is coupled to both the Payment and the Sale. However, if you assign the responsibility to the Sale to create the Payment, then you reduce the coupling of the Register because the Register is already coupled with the Sale due to previous responsibility.

Loose Coupling as I see it, is when you code against Interfaces. This is more like a type of Low coupling. In our domain discussion above, I might have a Register that only knows about the interface of a Sale (i.e. ISale) and this gives me the ability to replace the concrete class of Sale.

So is Interfaces more of an Indirection tool.

What about Interface Injection? I found I did not really get what Mr. Fowler was saying about interface injection. Any examples maybe on how to do Interface injection?

I have not used Spring.NET but have a Question. How do you bypass the Spring.NET framework Injection when you are Unit Testing the object?

On the subject of Mock Frameworks. Do you think that TypeMock.NET might lead developers down the wrong path when using the framework? The reason I am asking the question, is that TypeMock do not force you to use interfaces for external dependencies in order to mock the dependency. This might lead people down the path of writing coupled systems again.

I personally like NMock2, the expectation is so nice to read, ex:
Expect.Once.On( service ).Method( "MembershipRoles" ).WithAnyArguments().Will( Return.Value( response ) );

I have used Dependency Injection on several projects and it does make your life easy, especially when you do Test Driven Development.

I completely agree with your comment concerning TypeMock. I've only used it on a legacy project that was nearly impossible to be cleanly hooked into a test harness. By all means, something as powerful as TypeMock should be avoided unless absolutely necessary...e.g. with big, ugly, legacy systems. There's a great book on putting legacy systems into a test harness called "Working Effectively with Legacy Code" by Michael Feathers...definitely worth checking out - Feathers does with Legacy Code what Fowler did with Refactoring.

That's a very interesting point concerning "loose" coupling vs. "low" coupling. I've often used the two interchangably but I see your point. Wikipedia describes "loose" coupling to be more appropriate for remoting and SOA. Incidently, it also uses "loose" in describing "low" coupling.

Concerning your question of Spring .NET and Unit Tests... None of my primary unit tests are aware of Spring .NET. I have the unit tests take the responsibility of creating and injecting dependencies themselves. But I do have (OK, I sometimes have) a set of "smoke tests" that make HTTP requests to pages. I don't do anything more than making the HTTP request and seeing if an exception occurs. It's a quick and dirty way to make sure changes to the code aren't breaking web pages. On the flipside, web smoke tests are terribly slow and so usually only get run once a day by CruiseControl.NET. The rest of the time, I exclude the "Web Smoke Test" unit category.

I'll have to check out NMock2...I like the readable semantics of the example you provided.