Multiple Implementations of Same Interace - need to inject singletons of each implementation

Julie's Avatar


09 Jan, 2012 03:35 PM

I have two models that implement the same interface. They are singletons. I have two services, each needing an injection of one of the models. How do I map a singleton of each of the models in an interface-based way?

Ideally, I would like to do something along the lines of:

During context "bootstrap":

injector.mapSingletonOf(IMyClass, MyClassA, "MyClassA");
injector.mapSingletonOf(IMyClass, MyClassB, "MyClassB");

In Service 1:

[Inject(name="MyClassA")] public var myClassA:IMyClass;

In Service 2:

[Inject(name="MyClassB")] public var myClassB:IMyClass;

Is this possible?

  1. 1 Posted by Julie on 09 Jan, 2012 04:29 PM

    Julie's Avatar

    Nevermind - the above works famously!

  2. 2 Posted by Nicolas Bousque... on 10 Jan, 2012 01:35 PM

    Nicolas Bousquet's Avatar

    Named injection should be a last ressort measure. They greatly augment the risk of typos.
    If the two model implement the same interface, can't you inject a factory instead?

  3. 3 Posted by Julie on 10 Jan, 2012 03:03 PM

    Julie's Avatar

    I am only using the model in one command class and one service class. So, the named injection works fine for me. The DI container is a factory. Not sure at this point I need to roll my own factory.

  4. 4 Posted by Nicolas Bousque... on 11 Jan, 2012 03:44 PM

    Nicolas Bousquet's Avatar

    Golden rule: it's up to you to make the call :)
    Later on, if you find yourself locked in multiple injection problems again revolving around the same interface, you'll give it a second pass.
    Thanks for posting anyway, you made me cross the line from silent lurker to active commenter.

  5. Support Staff 5 Posted by Ondina D.F. on 11 Jan, 2012 04:25 PM

    Ondina D.F.'s Avatar

    Good decision, Nicolas:)
    The more people involved in discussions, the better.

  6. 6 Posted by Julie on 11 Jan, 2012 06:52 PM

    Julie's Avatar

    ok, since i started to feel bad for flippantly dismissing your idea, and since i was not aware that named injections were such an evil NO-NO, and since i pride myself in doing the right thing :), i decided to implement the injected factory. actually, a factory interface, thank ya very much! it is nice. thanks for the idea!

  7. Ondina D.F. closed this discussion on 17 Jan, 2012 10:58 AM.

Comments are currently closed for this discussion. You can start a new one.

Keyboard shortcuts


? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac