title: Ninject: Hint named dependency on parent class binding
body: <p>I have a class Consumer which itself requires a certain service IService. </p>
  
  <pre><code>interface IService{...}
  
  class ConcreteService : IService{...}
  
  class Consumer
  {
      public Consumer(string someString, IService service)
      {
          //Use service
      }
  }
  </code></pre>
  
  <p>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.</p>
  
  <pre><code>Bind&lt;IService&gt;().To&lt;ConcreteService&gt;().Named("MyService1");
  Bind&lt;IService&gt;().To&lt;ConcreteService&gt;().Named("MyService2");
  
  Bind&lt;Consumer&gt;().ToConstructor&lt;Consumer&gt;(c =&gt; new Consumer("Consumer1", c.Context.Kernel.Get&lt;IService&gt;("MyService1")));
  Bind&lt;Consumer&gt;().ToConstructor&lt;Consumer&gt;(c =&gt; new Consumer("Consumer2", c.Context.Kernel.Get&lt;IService&gt;("MyService2")));
  </code></pre>
  
  <p>Is this the preferred solution to deal with problems like this? I think there are a few alternatives.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <pre><code>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);
      }
  }
  </code></pre>
  
  <p>Is there a way to tell Ninject which dependency to use when there are multiple bindings defined for the same interface? </p>
  
  <pre><code>Bind&lt;Consumer&gt;().To&lt;Consumer().HeyNinjectUse(“MyService1”).IfThereAreMultipleBindingsOf&lt;IService&gt;();
  </code></pre>
  
  <p>Thanks for your help!</p>