Question

Using Robotlegs 2.0, is it possible to declare a singleton in a context and inject it in multiple classes, where each injection is requesting a different interface?

The class to inject:

 class MyClass implements IFoo, IBar {}

Injection site 1:

 class NeedFoo {
    [Inject]
    public var foo:IFoo;
 } 

Injection site 2:

 class NeedBar {
    [Inject]
    public var bar:IBar;
 } 

I want both injections to be for the same instance, but if I create two mappings, then each gets its own instance:

 injector.map( IFoo ).toSingleton( MyClass );
 injector.map( IBar ).toSingleton( MyClass );

So I ended up doing this:

 var instance:MyClass = new MyClass();
 injector.map( IFoo ).toValue( instance );
 injector.map( IBar ).toValue( instance );

Is there a way to just say that this object should be provided for any interface that it implements, rather than individually for each one?

Was it helpful?

Solution

Yes, it is, but it's a bit convoluted and really unclear ATM. We're going to provide some syntactic sugar for it in the future, but for the moment you can do this:

injector.map( IFoo ).toSingleton( MyClass );
var provider: DependencyProvider = injector.getMapping( IFoo ).getProvider();
injector.map( IBar ).toProvider( provider );

or

var provider: DependencyProvider = injector.map( IFoo ).toSingleton( MyClass ).getProvider();
injector.map( IBar ).toProvider( provider );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top