Using Dependency Injection to simplify parallel development in Flex and Apollo

In this article I’m going to show you how to use dependency injection in Flex and how to use that to support parallel development in Flex and Apollo. Along the way I’m also going to talk about the Data Access Object pattern.

The application we are going to look at is a very simple one. Basically it is a picture viewer that can either load a picture from the net or from the local file system. We are not going to get in to the actual loading, just looking at how you can create your application to support different loading mechanisms.

Before I show any code there are two design patterns that have to be discussed; Dependency Injection and Data Access Object.

Dependency Injection

Dependency Injection is an architectural pattern which can used to achieve loose coupling, simplify reuse and testing, and many other things you want to do to live up to the goals of object oriented design. Basically dependency injection is about programmatically configure your objects with the things they depend on, instead of having them create and retrieve their dependencies themselves.

In the opposite scenario, when the objects themselves are in charge of creating or retrieving other objects they need, you get a system which is tightly coupled, that is, too many objects depend directly on other specific objects. This makes it hard to reuse, hard to test and hard to change. Used right, dependency injection solves most of that.

In this article we use dependency injection in order to create a component which can be injected with objects that know how to load a picture. The component doesn’t know, nor does it need to know, which classes the objects belong to, just that they all implement a specific interface. The interface tells the component how to interact with the loading mechanism, but not how the loading is done. This way we can create many different picture loading implementations without having to change the component itself, and we can plug in a different version at a later date if needed.

To design the picture loading system we are going to use another design pattern which works very well together with dependency injection, the Data Access Object pattern.

Data Access Objects

If you have ever found yourself in the situation where you are developing an application and you need to change the backend half way, or perhaps the applications needs to be deployable on different backends to start with. In those cases the Data Access Object (DAO) pattern is useful. The purpose of the pattern is to have a single interface for access to data but allow for different concrete implementations. Using the DAO pattern you define an interface which your program will use to load data, and then one concrete implementation per backend or data source. This way the application doesn’t have to know which backend it is running on, and you can easily port it to another backend later without having to rewrite anything more than the code which creates the DAO.

The pattern originates in J2EE (i.e. Java web application development) where it is used to, for example, to insulate an application from different databases engines and their specific SQL dialects.

The DAO pattern works well with dependency injection, you can inject a concrete implementation into your objects without them having to bother with anything but the DAO interface. This way it can be used to simplify testing: create an implementation of a DAO which returns test data, so that the testing environment doesn’t need to be able to access a backend system in order to run (you usually want to test your algorithms and business methods, not the data in the backend).

Picture DAO

The application is going to show pictures, so it will need something that loads them for it. Using the DAO pattern we start by defining the interface of a picture loader, called PictureDao (my personal preference of symbol naming is to treat acronyms as words, thus “PictureDao” and not “PictureDAO“, so sue me). It doesn’t do much more than define a method for requesting the loading, a propery getter to access the picture and the event dispatched when the picture has loaded.

package {

import flash.events.IEventDispatcher;

import flash.display.Bitmap;

[Event(name="complete", type="flash.events.Event")] public interface PictureDao extends IEventDispatcher {

function loadPicture( ) : void ;

function get picture( ) : Bitmap ;

}

} This is the contents of PictureDao.as. If you wonder why I haven’t prefixed the interface name with “I” as is the convention in the ActionScript API:s I have written about that in an article called Interfaces in AS3, the gist of which is “If you prefix your interfaces with ‘I’, you have no idea how to use them”.

This interface will enable us work with any picture loading implementation without having to know anything about it. Regardless of the implementation we will know what it can do and how to work with it.

Concrete implementations

Let’s say that in the Flex web application we want to load the picture from a file on the server, but in the Apollo application we want to get the picture from the file system. To support these two scenarios I propose two concrete implementations: WebServicePictureDao and FileSystemPictureDao. The implementation isn’t really important at this point – in fact I will not show it at all, it is beyond the scope of this article. Of course, the Apollo application could load from the net as well, if you wanted to – the point is that you can create different implementations for different applications.

Picture viewer component

Let’s get started with the application. If you read my previous article on parallel development in Apollo and Flex you know that the best way to start is to make your application as a component, for example by extending the Canvas class instead of extending Application.

The main application component will contain a Image to display the picture and some code to support the injection of a DAO object. When the component recieves the DAO it will request that it starts loading a picture. The DAO will post an event when the picture is loaded, which the component recieves and shows the picture.

Note that the component doesn’t know how the DAO loads the picture, this makes the component reusable, which is exactly what we want.

<Canvas xmlns="http://.../mxml" xmlns:ix="*">
  <Script>
  <![CDATA[
  import flash.events.Event;

private var _pictureDao : PictureDao;

public function set pictureDao( pd : PictureDao ) : void { _pictureDao = pd; _pictureDao.addEventListener(Event.COMPLETE, onLoaded); _pictureDao.loadPicture(); }

private function onLoaded( event : Event ) : void { image.source = _pictureDao.picture; } ]]> </Script>

<Image id="image"/> </Canvas> This is the contents of Main.mxml, the MXML namespace has been shortened to avoid long lines.

When we have that out of the way, let’s see how do create the Apollo and Flex applications. This is where the actual dependency injection takes place. The main component (Main) expects something that implements the PictureDao interface as it’s pictureDao property. In the Apollo example I inject a FileSystemPictureDao:

<ApolloApplication xmlns="http://.../mxml" xmlns:ix="*">
  <ix:Main>
    <ix:pictureDao>
      <ix:FileSystemPictureDao />
    </ix:pictureDao>
  </ix:Main>
</ApolloApplication>
The MXML namespace has been shortened to avoid long lines.

In the Flex example I instead inject a WebServicePictureDao:

<Application xmlns="http://.../mxml" xmlns:ix="*">
  <ix:Main>
    <ix:pictureDao>
      <ix:WebServicePictureDao/>
    </ix:pictureDao>
  </ix:Main>
</Application>
The MXML namespace has been shortened to avoid long lines.

Now, if you should compile these two applications (provided you actually implement the DAO classes) they would look more or less the same, but would get their pictures from different places.

Extended use

Another useful thing is to make a configurable DAO, for example so that you can set the base URL on a case by case basis:

<ix:WebServicePictureDao>
  <ix:baseUrl>/pictures</ix:baseUrl>
</ix:WebServicePictureDao>

And you can reuse the DAO for multiple components, like this (say that you have a PicturePanel component that works similar to the main component above):

<ix:WebServicePictureDao id="pictureDao"/>

<ix:PicturePanel id="panelOne"> <ix:pictureDao>{pictureDao}</ix:pictureDao> </ix:PicturePanel>

<ix:PicturePanel id="panelTwo"> <ix:pictureDao>{pictureDao}</ix:pictureDao> </ix:PicturePanel>

Concusion

I have shown how you can reuse you components to support parallel development in Flex and Apollo using the dependency injection and DAO patterns. This way you will not have to support two different code bases to deploy an application on both platforms.

Dependency injection is more than DAO:s, but both patterns are very powerful and even more powerful when used together.

4 Responses to “Using Dependency Injection to simplify parallel development in Flex and Apollo”

  1. The Foundry » Blog Archive » Dependency injection examples in AS3 Says:

    [...] reading Theo Hultbergs posts about dependency injection in Flash and Flex I though it appropriate to post some examples of how I have [...]

  2. Arturas Says:

    You might want to take a look at our fast, compact and scalable .NET inversion of control (IoC, dependency injection) container – Winter4net. More details – www . winter4 . net

    This comment has been edited (the URL to the website was split so that it didn’t become a clickable link), I could not decide on whether it was spam or misdirected helpfulness. This is a post on DI in Flex, a .Net framework would not be very useful. –Theo

  3. Adobe AIR « Flex Generation Weblog Says:

    [...] Theo Hultberg :: Using Dependency Injection To Simplify Parallel Development In Flex And Apollo [...]

  4. Peter Says:

    http://code.google.com/p/legato/ simple IoC implementation for Flex

Leave a Reply