AS3 Dependency Injection and [Autowire]

Warning: This is long and probably VERY boring.. unless you are an AS3 junkie, and you’re interested in so called “lightweight micro-architectural frameworks” for Flash and Flex.

A couple of weeks ago I played around with Mate and Swiz. I already knew a little about Dependency Injection (in theory anyway), but playing with those two frameworks really drove the point home: applications are potentially MUCH easier to write, and much more flexible, when you take advantage of Dependency Injection.

If you’ve used PureMVC you might be familiar with writing code like this:

var myProxy:MyProxy = facade.retrieveProxy(MyProxy.NAME) as MyProxy;
myProxy.doSomethingAwesome();

This is sometimes referred to as the Model or Service Locator pattern. Firstly, it’s a little tedious to write. But more importantly, it puts the responsibility on your class to “fetch” the things it needs – not a good thing (especially from a testing point of view). From the “outside” you can’t see what your class is dependant on: you have to review the actual code in your class to see what it wants to pull in from the outside world.

It’s also a bit sneaky: to get something out, you have to know how it was put in – splitting and spreading knowledge across your codebase. Not pleasant.

Alternatively, you could use a Singleton to hang all your objects on. That would not be cool: link, link, link.

Enter Dependency Injection

Another solution is to declare certain properties on your class as dependencies to be “given” to you on (or just after) construction. A Dependency Injection framework will take care of managing these dependencies and providing you with what you need. Your class can then focus on doing it’s job instead of worrying about how to get the objects it needs.

I Like The Mediator Pattern

And I like the concepts in PureMVC: Specifically the Mediator, Command and Proxy patterns. I like clean view components with absolutely no framework or application code in them – as made possible by the Mediator pattern. I like Commands and I like binding them to system events. I like Proxies, who only communicate outwards, by dispatching events, and who’s APIs must be accessed directly by Commands and/or Mediator instances.

But I don’t like the use of Singletons or Multitons, the Service/Model locator pattern, the spreading of knowledge throughout the system by the Mediator and Proxy registration and retrieval mechanism (you have to know how something was put in to get it out again), and the custom Notification scheme and it’s associated methods: listNotificationInterests and handleNotification (with that nasty switch!).

So, I like PureMVC, I just think it could be improved for certain use cases. Now, obviously, improvement is subjective. Designing a framework is largely a balancing act: every decision has a pro and a con, and the framework architect must weigh up the pros and cons to steer the project in a chosen direction. That direction is determined by the architects vision of the most important use cases for the framework. I think that PureMVC has been brilliantly designed when stacked against it’s objectives. It’s been very carefully thought through, has an amazing author and community, sports great documentation, examples and utilities, and does it’s job well.

YALMAFRIA (Yet Another Lightweight Micro-Architecture For Rich Internet Applications)

Mate and Swiz can both do Dependency Injection. What I found interesting about the Dependency Injection in Mate is that it’s event based – this allows you to look at the event target to determine the instance that is currently being injected into. Using that (and a thing called an Object Builder in Mate) I was able to configure my application to automatically create Mediators for view components as they arrived on stage, and set references to the view components on the newly created Mediators.

It worked, but it seemed a little klunky, and still required a fair amount of code to map a Mediator Class to a view component Class (and any other dependencies). Regardless, it got me amped – using Dependency Injection and automatic Mediator registration I could remove most of the boring (and brittle) code from my projects.

I decided not to use Swiz or Mate in the end. Both offer nice solutions to some of the challenges of building RIA applications, but neither would make building my current application any quicker or easier.

Besides: I didn’t like the idea of using the display list as a system event channel, as in the case of Mate, or the concept of a central (Singleton) event dispatcher, as in the case of Swiz. And I didn’t want to put ANY application or framework code into my view components, as both seem to encourage.

Also, I wanted a framework that I could use for both Flex AND plain AS3 projects. I believe that this is possible with Swiz, but certainly not with Mate.

So, I looked for an AS3 Dependency Injection library to build a(nother) micro-architectural framework on top of..

Back to Dependency Injection

I tried Spring ActionScript (previously known as Prana) first. Immediately, two things bugged me about it: the use of external xml files to configure dependencies, and the side-effect of that requirement:

When compiling a SWF the compiler ignores Class definitions that are not directly referenced by the application. A small problem, easily solved, but an extra step none the less to ensure all necessary Classes are compiled. Loading your dependencies externally is groovy, fo sho, but I really don’t need that right now.

I believe you’d enjoy Spring ActionScript if you’re from Java land (hello there, have you played with Clojure yet? it got me all jazzed for a spell.. even though I didn’t build anything useful with it).

Anyhoo.. check this out if you are interested in Spring ActionScript and Autowiring: link

Or this, if you want to see how to do a similar thing with Swiz: link

Inspired by Guice

Next I checked out SmartyPants-IOC. I liked the vibe and proceeded to build my little framework with it.

RobotLegs AS3

I decided to call my framework RobotLegs. It’s very simple really. It contains two factories (and some Interfaces):

A Mediator Factory – for automatically creating and wiring up Mediators as view components arrive on Stage.

And a Command Factory – for binding commands to events.

Everything else is handled by Dependency Injection thanks to SmartyPants. Conceptually, the framework is much the same as PureMVC, but uses DI in place of a registry, and built-in Flash Events instead of Notifications.

I was able to migrate my current project over to Robot Legs (from PureMVC) in about a day. Not bad considering there were dozens of Commands, over 20 Mediators and around 10 Proxies to convert. It was a bit of a mission creating all the custom Event Classes to replace my Notifications though.

But it was certainly worth it. My application code has tidied up nicely. Many of my Mediators, Proxies and Commands have halved in size, due to the removal of lookup code and notification body casting.

RobotLegs?

The cool thing about Mediators that automatically wrap themselves around view components as they appear is that it greatly simplifies dealing with composite, lazily instantiated view components. I don’t need to worry about how a view component comes into being, I just set up a rule that ensures when that view components arrives I have a Mediator to link it back into the application. This is great for items inside Tab Navigators, Accordians, View Stacks etc.

It does present a little problem however: context. When you manually create and register a Mediator, you have the opportunity to give it some context, such as setting a property on it. Mediators that get automatically created make this a bit tricky. We could, of course, set that property on the view component, to be picked up by the Mediator on registration, but that’s not cool – view components should be self-contained, stand-alone widgets.

My current solution is to allow Mediators to request properties from parent Mediators. This is made possible by the Mediator Factory, with it’s dictionary of currently registered Mediators and view components, and a method declared by the Mediator Interface called “provideProperty”.

I plan on releasing Robot Legs once it has settled down a bit – using it in my current project has pointed out a great many things that I had overlooked initially. It won’t be everyone’s cup of tea – nothing is :)

UPDATE: RobotLegs 0.1, with demo Flex app, has been released. More info here:

info

Posted in Banter, Pijin, Robotlegs | Tagged , , , , , , , , , , | 28 Comments
  • Pingback: Pijin.net V3 Progress Update - 24 Feb 2009 « shaun smith()

  • Ben Smith

    From one smith to another we seem to be thinking the same page. I too have been working on a PureMVC implementation that that borrows the dependency injection from Swiz to create a new framework. I have managed to automatically register mediators and proxys when views are added to the stage and as you say “removing of most of the boring (and brittle) code”. The only contrast was using notifications that I quite like and that “nasty switch!” I find very clear, fast and easy to use, but I understand that it does bulk up your code somewhat. I look forward to taking RobotLegs for a walk and anything i can do to help just ask.
    Ben

  • Ben Smith

    From one smith to another we seem to be thinking the same page. I too have been working on a PureMVC implementation that that borrows the dependency injection from Swiz to create a new framework. I have managed to automatically register mediators and proxys when views are added to the stage and as you say “removing of most of the boring (and brittle) code”. The only contrast was using notifications that I quite like and that “nasty switch!” I find very clear, fast and easy to use, but I understand that it does bulk up your code somewhat. I look forward to taking RobotLegs for a walk and anything i can do to help just ask.
    Ben

  • http://shaun.boyblack.co.za/blog/ shaun

    Hi Ben,

    Awesome! Out of interest, are you building “on top of” PureMVC, or is it a completely standalone framework you are making?

    I considered building RobotLegs as a PureMVC plugin/utility, but thought it might get a little too complicated. Besides, I wanted something that could be modular (sub applications living side-by-side) without being overly complex – the fact that, at the core, PureMVC relies on Singletons, brings unneeded complexity to the table, necessitating things like “Pipes” and “Cores” which I feel are over engineered (and only exist because of the Singletons in the first place!).

    With regards to Notifications: I’m still not sure where I stand on this. Having converted to standard Flash event handlers, I’m beginning to feel that perhaps Notifications are not so bad after all! Event handlers add their own bloat. And, I have to create a custom Event Class for each distinct type of message that I want to broadcast.. More code than I’m saving by removing the listNotificationInterests method!

    On the other hand, it’s nice not having to cast the Notification payload all over the place. A custom Event will have any payload properties strictly typed to start with.

    For the most part, I’m ready to release RobotLegs into the wild. Initially, I was going to wait for SmartyPants to hit it’s 1.0 Release, but I don’t think it matters too much actually. What I would like to do, however, is build a sample application to demo the framework before I put it out there.. which might take me a little while – I’m right in the middle of a pretty fat project right now :)

    Another decision is whether to host the code on Google Code (SVN vibes) or GitHub (Git vibes). I have the feeling that Flash devs are more comfortable with SVN at the moment. On the other hand, GitHub would make it very easy for anyone to pick up the project and take it another direction.

    Anyhow, enough of this, I must get back to work!

    Cheers,
    Shaun

  • http://www.boyblack.co.za shaun

    Hi Ben,

    Awesome! Out of interest, are you building “on top of” PureMVC, or is it a completely standalone framework you are making?

    I considered building RobotLegs as a PureMVC plugin/utility, but thought it might get a little too complicated. Besides, I wanted something that could be modular (sub applications living side-by-side) without being overly complex – the fact that, at the core, PureMVC relies on Singletons, brings unneeded complexity to the table, necessitating things like “Pipes” and “Cores” which I feel are over engineered (and only exist because of the Singletons in the first place!).

    With regards to Notifications: I’m still not sure where I stand on this. Having converted to standard Flash event handlers, I’m beginning to feel that perhaps Notifications are not so bad after all! Event handlers add their own bloat. And, I have to create a custom Event Class for each distinct type of message that I want to broadcast.. More code than I’m saving by removing the listNotificationInterests method!

    On the other hand, it’s nice not having to cast the Notification payload all over the place. A custom Event will have any payload properties strictly typed to start with.

    For the most part, I’m ready to release RobotLegs into the wild. Initially, I was going to wait for SmartyPants to hit it’s 1.0 Release, but I don’t think it matters too much actually. What I would like to do, however, is build a sample application to demo the framework before I put it out there.. which might take me a little while – I’m right in the middle of a pretty fat project right now :)

    Another decision is whether to host the code on Google Code (SVN vibes) or GitHub (Git vibes). I have the feeling that Flash devs are more comfortable with SVN at the moment. On the other hand, GitHub would make it very easy for anyone to pick up the project and take it another direction.

    Anyhow, enough of this, I must get back to work!

    Cheers,
    Shaun

  • Ben Smith

    Hi Shaun,

    Yes my implementation was built directly on the PureMVC Standard framework with an eye to break it out in to sub packages latter. So i added a new pattern into the org.puremvc.as3.patterns.ioc and then added methods to my AppliactionFacade.initializeControls() ioc.autoWireView(view,mediator) method to map views to their mediators though I like the idea of using the Factory for this. I’m still in the proof of concept stages at the moment so still need to refactor the code some what.

    Yes i hear what you’re saying about creating custom class events but have you considered lifting the mx.events.DynamicEvent from the Flex Framework? of course you end up with a generic Object for your payload that you might still have to cast but it would dynamically cut down the laborious task of event class creation.
    I don’t have my code to hand but when i get a change ill get a sample app over to you.

    SVN vibes are good with me, not looked into GitHub yet

    Yep best get back to work also.

    Ben

  • Ben Smith

    Hi Shaun,

    Yes my implementation was built directly on the PureMVC Standard framework with an eye to break it out in to sub packages latter. So i added a new pattern into the org.puremvc.as3.patterns.ioc and then added methods to my AppliactionFacade.initializeControls() ioc.autoWireView(view,mediator) method to map views to their mediators though I like the idea of using the Factory for this. I’m still in the proof of concept stages at the moment so still need to refactor the code some what.

    Yes i hear what you’re saying about creating custom class events but have you considered lifting the mx.events.DynamicEvent from the Flex Framework? of course you end up with a generic Object for your payload that you might still have to cast but it would dynamically cut down the laborious task of event class creation.
    I don’t have my code to hand but when i get a change ill get a sample app over to you.

    SVN vibes are good with me, not looked into GitHub yet

    Yep best get back to work also.

    Ben

  • http://diamondtearz.org/blog diamondTearz

    Is this payback for my article about the GUI stuff sucking you in. It’s as if you knew I’d been looking for a way to burn hours today reading and Googling. I’ve been on the fence about whether the gain in productivity is enough to warrant learning yet another framework. That sound would be you knocking an innocent man off a fence.

  • http://diamondtearz.org/blog diamondTearz

    Is this payback for my article about the GUI stuff sucking you in. It’s as if you knew I’d been looking for a way to burn hours today reading and Googling. I’ve been on the fence about whether the gain in productivity is enough to warrant learning yet another framework. That sound would be you knocking an innocent man off a fence.

  • http://shaun.boyblack.co.za/blog/ shaun

    Haha! Well good, cos that Immediate-Mode GUI stuff threw me into a bit of a spin this morning! I had to let it go for fear of losing the whole day to “research” 😉

  • http://www.boyblack.co.za shaun

    Haha! Well good, cos that Immediate-Mode GUI stuff threw me into a bit of a spin this morning! I had to let it go for fear of losing the whole day to “research” 😉

  • Benoit Jadinon

    A Release ! A Release ! A Release !

  • Pingback: AS3 Dependency Injection Framework: SmartyPantsIOC - Released! « shaun smith()

  • http://www.robmccardle.com/ Rob McCardle

    Nice roundup, cheers for sharing. Have you seen Fabrication?

    Reflexive Mediator Notification gets rid of most of the aspects of PureMVC that you don’t like, it really does rock.

    Code of Doom has more on this:
    http://codeofdoom.com/wordpress/2009/01/27/fabrication-puremvc-cleaned-up/

    The Google Code docs are also well worth a read http://code.google.com/p/fabrication/

    I like it a lot and intent to post some of my work with it soon. Cheerio

  • http://www.robmccardle.com Rob McCardle

    Nice roundup, cheers for sharing. Have you seen Fabrication?

    Reflexive Mediator Notification gets rid of most of the aspects of PureMVC that you don’t like, it really does rock.

    Code of Doom has more on this:
    http://codeofdoom.com/wordpress/2009/01/27/fabrication-puremvc-cleaned-up/

    The Google Code docs are also well worth a read http://code.google.com/p/fabrication/

    I like it a lot and intent to post some of my work with it soon. Cheerio

  • http://shaun.boyblack.co.za/blog/ shaun

    Hi Rob,

    I’ve been keeping an eye on Fabrication for quite a while, but haven’t actually built any real-world projects with it. It definitely looks like it does a good job of minimizing PureMVC boilerplate. Next time I have to build a PureMVC app I’ll certainly give it a spin.

    Cheers,

  • http://www.boyblack.co.za shaun

    Hi Rob,

    I’ve been keeping an eye on Fabrication for quite a while, but haven’t actually built any real-world projects with it. It definitely looks like it does a good job of minimizing PureMVC boilerplate. Next time I have to build a PureMVC app I’ll certainly give it a spin.

    Cheers,

  • Simen

    Really curious about Robot Legs, I’ve been reading a lot of Misko Hevery lately and it really inspired me to redo our in-house framework with lose coupling using DI.

    Only thing that put me off about SmartyPants is that it doesn’t (yet?) support Constructor Injection, and that again can lead to stuff being executed out of order; curiously enough, the year old project DI-AS3 seems to support it using a simpler syntax.

  • Simen

    Really curious about Robot Legs, I’ve been reading a lot of Misko Hevery lately and it really inspired me to redo our in-house framework with lose coupling using DI.

    Only thing that put me off about SmartyPants is that it doesn’t (yet?) support Constructor Injection, and that again can lead to stuff being executed out of order; curiously enough, the year old project DI-AS3 seems to support it using a simpler syntax.

  • http://shaun.boyblack.co.za/blog/ shaun

    Hi Simen,

    Ah yes, lot’s of great info on Misko’s blog!

    Funnily enough, I’m thinking of looking for a different DI framework once I’ve finished the RobotLegs demo – but not so much because of the setter injection (or lack of constructor injection), but rather because SmartyPants has a couple of Flex dependencies that make it a little bigger than it could be if those parts were “opt-in”.

    Initially I was put off by the lack of constructor injection, but in practice I’m finding that it’s quite convenient for my framework – having to funnel all dependencies through a constructor (and then set private properties) requires quite a bit of extra coding.

    Whilst it’s definitely a safer approach to use constructor injection (keeping your properties private and ensuring you don’t forget to inject things) I’m actually quite enjoying just declaring my dependencies as public properties at the top of my classes.

    I’m hoping to release RobotLegs in the next couple of hours… not thoroughly documented.. and certainly not a 1.0 release.. but it should be enough to get going with if you have experience with PureMVC.

    Cheers,

  • http://www.boyblack.co.za shaun

    Hi Simen,

    Ah yes, lot’s of great info on Misko’s blog!

    Funnily enough, I’m thinking of looking for a different DI framework once I’ve finished the RobotLegs demo – but not so much because of the setter injection (or lack of constructor injection), but rather because SmartyPants has a couple of Flex dependencies that make it a little bigger than it could be if those parts were “opt-in”.

    Initially I was put off by the lack of constructor injection, but in practice I’m finding that it’s quite convenient for my framework – having to funnel all dependencies through a constructor (and then set private properties) requires quite a bit of extra coding.

    Whilst it’s definitely a safer approach to use constructor injection (keeping your properties private and ensuring you don’t forget to inject things) I’m actually quite enjoying just declaring my dependencies as public properties at the top of my classes.

    I’m hoping to release RobotLegs in the next couple of hours… not thoroughly documented.. and certainly not a 1.0 release.. but it should be enough to get going with if you have experience with PureMVC.

    Cheers,

  • Pingback: RobotLegs - An AS3 MVCS framework for Flash and Flex Applications inspired by PureMVC « shaun smith()

  • Simen

    As you hint towards, none of the DI frameworks seem to fit the AS3/Flex bill perfectly, I personally think all the frameworks borrow too much inspiration from existing frameworks that were written for other languages.

    I’ve thought about writing a similar framework to DI-AS3 where you have constructor and setter injection plus Guice style annotations, let me know if you’re considering the herculian effort and I’d be more than happy to contribute!

  • Simen

    As you hint towards, none of the DI frameworks seem to fit the AS3/Flex bill perfectly, I personally think all the frameworks borrow too much inspiration from existing frameworks that were written for other languages.

    I’ve thought about writing a similar framework to DI-AS3 where you have constructor and setter injection plus Guice style annotations, let me know if you’re considering the herculian effort and I’d be more than happy to contribute!

  • Pingback: Flexible RIA Architecture: PureMVC and Mate « shaun smith()

  • Benoit Jadinon

    A Release ! A Release ! A Release !

  • Pingback: Flex Frameworks – PuremVC, Mate, Cairngorm and Robotlegs | Wet Feet - Online Marketing and Technology Blog()

  • Worldwarwon

    wow. you are indeed a machine. I bet you actually have real robotic legs under that pin-striped disguise?