Search code examples
c#dependency-injectionninject

Ninject - Bind different interfaces implementations to the same class


I'm new to DI (using Ninject) and just started to learn the concepts, but I've been scratching my head for a while to understand this:

Suppose I have DIFFERENT usage of the same class in my program (ProcessContext in the example below).

In the first class (SomeClass) : I would like to inject Implement1 to ProcessContext instance.

In the second class (SomeOtherClass) : I would like to inject Implement2 to ProcessContext instance.

How should I perform the bindings using Ninject ?

public class Implement1 : IAmInterace
{
   public void Method()
   {
   }
}

public class Implement2 : IAmInterace
{
   public void Method()
   {
   }
}

public class ProcessContext : IProcessContext
{
   IAmInterface iamInterface;
   public ProcessContext(IAmInterface iamInterface)
   {
      this.iamInterface = iamInterface;
   } 
}

public class SomeClass : ISomeClass
{
    public void SomeMethod()
    {
        // HERE I WANT TO USE: processcontext instance with Implement1
        IProcessContext pc = kernel.Get<IProcessContext>();            
    }
}

public class SomeOtherClass : ISomeOtherClass
{
    public void SomeMethod()
    {
        // HERE I WANT TO USE: processcontext instance with Implement2
        IProcessContext pc = kernel.Get<IProcessContext>();            
    }
}

Solution

  • You could use named bindings for this.

    e.g. something like:

    Bind<IProcessContext>()
        .To<ProcessContext>()
        .WithConstructorArgument("iamInterface", context => Kernel.Get<Implement1>())
        .Named("Imp1");
    
    Bind<IProcessContext>()
        .To<ProcessContext>()
        .WithConstructorArgument("iamInterface", context => Kernel.Get<Implement2>())
        .Named("Imp2");
    
    kernel.Get<IProcessContext>("Imp1");