Reputation: 52
I need to compose an instance conditionally depending on the caller.
In some cases I need a composite object instances with a "deep" type "NullService"
in other cases I instead inject a "ConcreteService"
I expect something like this:
Get<Root>.with(NullService)
or
Get<Root>.with(ConcreteService)
or better still if one could bind the construction so that it dated back to the calling context
Bind<IService>.to(ConcreteService).
Bind<IService>.to(NullService).only.whenCallerIsTypeOf(CallerWhosNeedsANullService)
is it possible?
Upvotes: 1
Views: 304
Reputation: 32725
There are two ways:
Use an own condition in case you can calculate which one should be used:
Bind<IService>.To(NullService)
.When(ctx => IsCallerWhosNeedsANullService(HttpContext.Current.Request));
Use Named bindings
Bind<Root>().ToSelf().Named("DefaultRoot");
Bind<Root>().ToSelf().Named("NullRoot");
Bind<IService>.To(ConcreteService);
Bind<IService>.To(NullService).WhenAnyAnchestorNamed("NullRoot");
Get<Root>("NullRoot");
Upvotes: 1