How do you use injector.mapSingleton/mapSingletonOf with abstract classes & interfaces?

Dave's Avatar

Dave

27 Aug, 2010 09:17 AM

Hi there,

I'm looking at the best practices document which says:

"mapSingletonOf is much like mapSingleton in functionality. It is useful for mapping abstract classes and interfaces, where mapSingleton is for mapping concrete class implementations."

I've got 2 different services, each of which extend the same abstract class (AbstractFileLoaderService) and implement the same interface (IFileLoaderService). If I try and use mapSingletonOf like so:

injector.mapSingletonOf(IFileLoaderService, ConcreteServiceA);
injector.mapSingletonOf(IFileLoaderService, ConcreteServiceB);

and then I inject those services into commands like this:

[Inject] public var concreteServiceAInstance:IFileLoaderService;

and

[Inject] public var concreteServiceBInstance:IFileLoaderService;

What ends up happening is the injector doesn't know which concrete service it's supposed to inject which it encounters the interface in the inject commands so it does the same one twice. While it makes sense to me why it does this, I'm not sure what the proper way to resolve this is. I can refactor it to use injector.mapSingleton and just inject the concrete classes and everything works, but doesn't this go against the whole point of mapSingletonOf and interfaces?

  1. 1 Posted by r.moorman on 27 Aug, 2010 09:28 AM

    r.moorman's Avatar

    You can use named injection:

    injector.mapSingletonOf( IFileLoaderService, ConcreteServiceA, 'nameOfA' );
    injector.mapSingletonOf( IFileLoaderService, ConcreteServiceB, 'nameOfB' );
    

    In your injected class retrieve the injection by [Inject name="nameOfA"].

    Hope this solution solves your problem.

  2. 2 Posted by Dave on 27 Aug, 2010 09:43 AM

    Dave's Avatar

    Perfect! Thanks for the fast reply.

  3. Dave closed this discussion on 27 Aug, 2010 09:43 AM.

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

Keyboard shortcuts

Generic

? 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