Dependency Injection (& Small Furry Animals)

Dependency Injection (DI) is a game changing design pattern that most programmers should have in their toolbox. DI was initially known as Inversion of Control (IoC), but because frameworks inherently invert some sort of control Martin Fowler proposed the naming switch to DI in his canonical post on the subject to better describe which aspect of control is being inverted. There are plenty of tutorials on DI that are extremely helpful when ramping up on the topic, although some of them are either tightly coupled to a particular language or framework while others can be a bit lengthy. For that reason I thought I would take the time to write a quick post that explains the concept of DI at a high level, in a (somewhat) concise fashion. I’ll try to explain things in a way that is language agnostic, but I will use Java for my initial example. After that I’ll touch on ways to use DI in a few common languages, and then I’ll close by listing a few reasons why DI is cool.

To illustrate what DI is all about, let’s suppose that I’m writing a Java application that makes small furry animals sing and dance on the screen (because everyone loves a minstrel marmot). I begin by creating a SmallFurryAnimal Interface like so:

Interface SmallFurryAnimal {
  void Sing();
  void Dance();
}

I then create a couple of animal Classes called Marmot and Squirrel that implement SmallFurryAnimal with their own animal specific implementation of Sing and Dance. I tie everything together in a main method that looks like this:

Class Application {
  public static void main(String [ ] args) {
    while (true) {
      Marmot.Sing();
      Marmot.Dance();
      Squirrel.Sing();
      Squirrel.Dance();
    }
  }
}

When I run javac to compile my application to bytecode I need to be sure to pass the source files for Marmot and Squirrel to compile Application because they are hardcoded compile time dependencies. When I run the application using java I also need to be sure that the ClassLoader is able to load Squirrel and Marmot. This is all fine and dandy until I realize that I want to give people who use my application the ability to design, implement, and plugin their own arbitrary small furry animals without having to worry about recompiling or even knowing about the rest of my application. Essentially I want to do the following:

Class Application {
  public static void main(String [ ] args) {
    while (true) {
      for (all the aniamls that I inject at runtime) {
        SmallFurryAnimal.Sing();
        SmallFurryAnimal.Dance();
      }
    }
  }
}

With these changes I’m only bound to the interface for SmallFurryAnimal, not any particular implementation. I’m free to code up animals to my heart’s content, and I can use DI to inject them into my application at runtime.

It turns out that this kind of ability to inject dependencies into an application at runtime is very common for all sorts of applications. One very common example is applications that run workflows and allow users to inject custom workflow tasks. Another similar example is a state machine application that allows users to inject custom states behaviors that relate to states. In fact almost any time you implement an interface or derive from a base class may be a candidate for injecting the dependency on the implementation at runtime unless the number of possible or necessary implementations is of a relatively small fixed size that isn’t likely to change.

It’s possible to use DI in Java without taking advantage of any additional frameworks by using Reflection to crack open Class Files and look for Classes that implement a specific interface. The most common way to use DI in Java is Spring, a popular Java Framework targeted at a wide array of Java deployment use cases. One of the things that Spring provides is an IoC container which provides the ability to load Java objects using Reflection (typically by specifying which objects to load in configuration) and handles managing the lifecycle of those objects.

C# is obviously very similar to Java, and it allows you to implement DI using Reflection. .NET has also introduced the Managed Extensibility Framework which allows usage of the DI pattern without configuration by using class attributes to tell the Composition Container what to load at runtime.

If you’re using dynamic programming languages like Perl or Ruby then DI is essentially baked in, you’re probably already using it whether or not you realize it.

There are a bunch of reasons why DI is super important, and why many programmers who first stumble on the pattern feel like it’s a game changer. It improves testability by providing the ability to inject mock objects during test execution. It improves reusability of code by allowing developers to build components once and dynamically injected them into multiple applications, and by allowing application consumers to inject objects that are specific to their requirements. It makes code more readable by making dependencies explicit in configuration or metadata. It makes applications easier to deploy or upgrade by guaranteeing loose coupling with dependencies so that either the application or any injected object can be deployed in isolation.

It’s not the only way to accomplish these objectives, but it’s certainly a great way to do so. Hopefully this quick overview has served to help introduce you to the DI pattern, and provided some useful links in case you want to dig deeper.

Leave a Reply