AS3 Dependency Injection (DI)

Dependency injection (DI) is a method of supplying external references to components. Every time you pass a parameter through a constructor you are in effect injecting dependency.

Reducing the number of dependencies is seen as a good thing as the component becomes further decoupled and more modular. To achieve this a Dependency Injection Framework can be used.

DI Frameworks tend to makes use of a technique called Inversion of Control (IoC) which helps separate specific code from generic code leaving your components elegant and dependency free.

Allot of people seem skeptical of the benefits of DI, but it appears only through its use can you begin to see its benefits.

For a better argument read this thread on the robotlegs google group that helped to sway others.

This video gives an incite into why Dependency Injection is useful. Its not AS3 specific but the principles described are the same all be it extremely simplified!!.


How do we implement DI with AS3?

Well most AS3 DI frameworks go beyond basic constructor injection, instead opting for a meta data injection method, which is where DI becomes a powerful tool in AS3. To achieve this with best results a DI framework is required that will make use of the describeType method to retrieve an XML description of a class. The framework will identify [Inject] meta tags and then inject the instance that is mapped to it. This may sound complicated but John Lindquist recently produced a video tutorial on how robotlegs works and in the process covered the basic methods of dependency injection in the 4th installment. shown here


Here are some AS3 DI frameworks to try;

Swift Suspenders by Till Schneidereit. | repository | blog | twitter
Swift suspenders seems to be the most commonly used framework and is favoured by the robotlegs platform.

Smarty Pants by Josh MacDonald. | repository | twitter

Funk AS3 by Joa Ebert. | repository | blog | twitter
A meta free injection framework. Funk doesn’t use the describeType method used by most injection frameworks and saves on initial overhead, however gains overhead by way of a method call for each injection.

Michael Cann blogged about his experience with Funk with a brief example of use.

Foot note: I read a post by Josh MacDonald on the robotlegs google group and he suggested reading Dependency Injection Design patterns using Spring and Guice Dhanji R. Prasanna Foreword by Bob Lee

Allot of the aforementioned frameworks take inspiration from DI frameworks developed outside of actionscript for example the Spring framework or Googles Guice developed for Java . Perhaps for a better understanding of dependency injection reading about these other frameworks will help.

Comments (View)
blog comments powered by Disqus

posted : Sunday, February 6th, 2011