I have a class Consumer which itself requires a certain service IService.
interface IService{...}
class ConcreteService : IService{...}
class Consumer
{
public Consumer(string someString, IService service)
{
//Use service
}
}
However, in my system I need different instances of the same IService implementation. There are also different consumer instances which require a certain Service instance. Some consumers require MyService1 others require MyService2. To solve this, I created named bindings from IService to ConcreteService. I wired it up like this.
Bind<IService>().To<ConcreteService>().Named("MyService1");
Bind<IService>().To<ConcreteService>().Named("MyService2");
Bind<Consumer>().ToConstructor<Consumer>(c => new Consumer("Consumer1", c.Context.Kernel.Get<IService>("MyService1")));
Bind<Consumer>().ToConstructor<Consumer>(c => new Consumer("Consumer2", c.Context.Kernel.Get<IService>("MyService2")));
Is this the preferred solution to deal with problems like this? I think there are a few alternatives.
First, I could create two different subclasses Consumer1 and Consumer2 and use the [Named(..)] Attribute on the dependency. But I don’t really like the DI framework leaking into my model. Besides this, it could result in a tremendous amount of subclasses.
The other option that I have is creating an additional class ServiceAggregator which gets all bindings for IService injected. The Consumer class could then use the ServiceAggregator to find the appropriate Service. I would use such an approach if the Consumer class required another Service at runtime, but I don’t think it makes much sense if the dependency could be resolved during object instantiation.
class ServiceAggregator
{
public ServiceAggregator(IService[] services)
{...}
public IService GetService(string serviceIdentifier)
{...}
}
class Consumer
{
IService myService;
public Consumer(string someString, string serviceName, ServiceAggregator aggregator)
{
myService = aggregator.GetService(serviceName);
}
}
Is there a way to tell Ninject which dependency to use when there are multiple bindings defined for the same interface?
Bind<Consumer>().To<Consumer().HeyNinjectUse(“MyService1”).IfThereAreMultipleBindingsOf<IService>();
Thanks for your help!