IoC and the Dependency Injection Pattern in Flex

Within the vast catalog of Design Patterns available to software developers today, one of the most important to consider when designing an enterprise class RIA is the Dependency Injection Pattern.

Dependency Injection, a term originally coined by Martin Fowler in his well known article Inversion of Control Containers and the Dependency Injection Pattern, is a more specific term for what is otherwise known as Inversion of Control or IoC.

Fowler’s assessment of Inversion of Control containers concluded that the name itself – Inversion of Control – was too generic, thus as a result from his discussions with various IoC advocates they settled on the more specific term Dependency Injection, also known as DI for short. The terms Inversion of Control (IoC) and Dependency Injection (DI) are commonly used interchangeably to describe the same underlying design principle of separating configuration from implementation.

There are three basic forms of Dependency Injection, which are generally referred to as type 1 IoC (Interface Injection), type 2 IoC (Setter Injection) and type 3 IoC (Constructor Injection). Before diving into the specifics of how to implement the various forms of DI, I will first discuss what Dependency Injection is on a conceptual level as well as what each specific form means. The examples outlined here are in ActionScript 3, however it is important to keep in mind that like most Design Patterns Dependency Injection applies to any language which supports an Object Oriented Model.

At the most basic level Dependency Injection can be explained as a way of decoupling classes from their dependencies by injecting the dependencies into them rather than having the classes directly reference specific implementations. A class which directly references other classes is coupled to those classes – these are the dependencies. However a class which does not reference any other classes would probably not be very useful. At some point the dependencies need to be made. Dependency Injection is a solution to how those dependencies are made, and the manner by which they are provided.

For example, consider the following class which illustrates a typical example of a class’s dependency on another class:

From looking at the code above the dependencies are pretty obvious; the ConfigurationManager class is dependent on the XMLConfiguration class. Now this type of dependency is quite typical so at this point you may be asking what is wrong with doing this?

The first problem is that the config property is defined as a concrete implementation:

This violates a fundamental OO principle:

Program to interfaces, not implementations.

More importantly and perhaps pertinent to the topic at hand is that it also isn’t very hard to imagine that at some point we may want to load a configuration from some other means, such as a properties file, a remote service and so on. In order to do so we would need to modify the class, and from this we can deduce that the class does not scale very well.

So we could begin improving our current implementation by simply refactoring the ConfigurationManager class to define the config property as an abstraction, say IConfiguration:

As you can see this is certainly a step in the right direction, however the underlying problem still remains; we are still instantiating an instance of XMLConfiguration directly in the ConfigurationManager – and that is exactly what Dependency Injection is all about: providing a solution to the recurring problem of managing dependencies between classes, and how those dependencies are provided.

When implementing the Dependency Injection Pattern in an application you do so by creating a context (configuration) which defines all dependencies in an application as well as an Assembler which is responsible for assembling the mappings and associations between objects and their dependencies. This is done by utilizing any combination of the three forms of DI; Interface Injection, Setter Injection and Constructor Injection. Below is a brief description of each form:

Interface Injection
Interface Injection is the process by which all dependencies are injected into an object via an interface. For example, the ConfigurationManager example above could implement an interface which defines the operations needed to inject the appropriate Configuration implementation.

Setter Injection
Setter injection as you may have guessed is the process of injecting dependencies via public setters; both explicit or implicit. Using Setter Injection the ConfigurationManager could provide public setters from which an Assembler could inject the appropriate Configuration implementation.

Constructor Injection
Again as you may have guessed Constructor Injection is the process of injecting dependencies via arguments in the class constructor. Using Constructor Injection the concrete Configuration could just as easily be injected.

Both Constructor and Setter Injection are by far the preferred forms of Dependency Injection. Interface Injection has some major drawbacks as it somewhat leads to convoluted code since multiple additional interfaces need to be defined and implemented. The fact that “special” types need to be created and implemented in order to facilitate DI using Interface Injection greatly limits the potential for its use.

There are numerous frameworks for various platforms which provide out of the box Dependency Injection implementations for all three forms of DI. All of these frameworks handle the wiring necessary for easily implementing Dependency Injection in an application, the most notable being the Spring Framework for Java/J2EE. There are also quite a few DI solutions for Flex and ActionScript applications as well. Optionally you could choose to roll your own however I would first suggest investigating some of the frameworks which are currently available as they more than likely provide what you need. The Prana Framework by Christophe Herreman is a good choice as it is one of the most prevalent DI solution available at the moment for Flex.

Using the ConfgurationManager example from above I have provided a basic example application which demonstrates how to implement Dependency Injection utilizing the Prana framework. The example application uses constructor injection to provide a concrete Configuration to the ConfigurationManager, however I encourage you to experiment with the other mechanisms of injection as well. The example is intentionally kept very simple in that it is only intended to convey the basic concepts of DI and how to use it in Flex with Prana, from this you should have a good understanding of how to implement DI in a larger context.

{ 15 comments ... add another one! }

  1. Very well written and informative, thanks eric.

  2. Hi Eric,
    thanks for this article and the example.
    What about changing config.properties or config.xml at runtime, i.e. when i need to change the logLevel for some circumstance ? Currently this is not possible because these files are not available in the compiled \bin directory (of course not, they are embedded).
    Is there a way to make them available/modifiable at runtime ?

    Best regards
    valley

  3. Hey Valley,

    The implementation of the example classes is not important and is not meant to be viewed as code which would be used in a real application. As I mention in the post the example is intentionally very simple as the goal is not to get bogged down with implementation details as that would only distract from the actual topic.

    However with that being said if you were to take this example and turn it into an actual usable API you could simply have each concrete configuration load the files (resources, XML, etc) at runtime. The actual files themselves would also be passed into the Configuration classes using DI via the application context. To change the value at runtime externally you could do so by passing in the value through the query string, a service etc.

    Thanks,
    Eric

    Thanks,
    Eric

  4. Hi Erick, thanks for the great post…
    A while ago I did something similar to your proposal, trying to “inject” a class that was implementing an interface inside a library into another class using a setter.
    I had the injection done by another class that loaded a XML file on the fly, specifying the default class to inject (sort of what spring does) and with the use of reflection I was able to load the class dynamically and use all the services exposed by the interface from that implementation…
    Since I was using RSL and dynamic linkage I was able to upload my library with a new class implementation, update my XML with that new implementation set as the default and execute the application without having to compile anything else other than my Library…
    Seems like Prana takes care of that extra class I created, definitely will pay attention to it…

  5. Good post! Covered this post in a featured post on riarevolution. Here is the link : http://riarevolution.com/2008/09/22/ioc-and-dependency-injection-in-flex/

  6. Hi Eric

    thanks for a very nice and useful post.

    One comment that i thought of, it doesn’t seem to me that a drawback of the Interface injection is the need to create more Interfaces, since we still need to create those for Setter and Constructor Injection.

  7. Hey Ahmed,

    Good point, the reason why Interface injection is not the most desirable mechanism of DI is that in a large project you may need to potentially create many, many additional interfaces in which their only purpose is to facilitate DI. These additional interfaces add to the complexity of the codebase and IMHO they are coupling your application code to the framerwork. A constructor or setter which accepts references to other objects is very common so this additional overhead is less intrusive than interface injection.

    Best,
    Eric

  8. Hey Eric,

    This is a really nice post about IoC and prana. Thank you!

    I was wondering if you have taken a look at the swiz framework, which also implements IoC however via annotations versus xml. If you have, would you mind sharing your thoughts about swiz and how it compares to prana? I do not have much experience with either of the frameworks, especially swiz, so any thoughts would be appreciated! :)

    Thanks and keep it up, man!

  9. Thanks Eric. Actually I didn’t know much about the injection pattern before, but I did lots of reading after I saw this post. And now I do understand the need for more interface to apply the interface injection.

  10. Hi Martin,

    I have implemented a sample application using Swiz.

    http://www.hemtalreja.com/?p=258

    Enjoy!!!
    -Hem

  11. For those interested in Flex and IOC, Flicc – http://flicc.sourceforge.net/ – is also worth a look. Since it’s configuration is based on MXML rather than XML, you get some extra comile time checking as well as a more concise markup.

  12. Another very good Flex framework is Mate.
    It too is MXML based.

    http://mate.asfusion.com/

    Greg

  13. Thanks for taking the time to put this explanation of Dependency Injection together. It helped clarify a lot of the details.

  14. Excellent post! Simple and informative.

    Thanks.

{ 0 Pingbacks/Trackbacks }