Ninject bind mulitple implementations to an interf

2019-08-12 00:50发布

问题:

I'm looking at this tutorial, but not quite understanding how to create a factory that can provide me separate implementations of an interface.

http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/

public class IJob {
  ...
}

public class JobImpl1 : IJob {
  ...
}

public class JobImpl2 : IJob {
  ...
}

using (IKernel kernel = new StandardKernel()) {
    kernel.Bind<IJob>().To<JobImpl2>(); 
    var job = kernel.Get<IJob>();
}

My goal is to make a factory class that wraps this Ninject Kernel so I can provide different implementations of my IJob interface depending on whether I'm in a unit test environment vs a live environment. However, I also want to keep the Ninject hidden inside the factory wrapper so that the rest of the code will not depend on Ninject.

回答1:

There is a separate extension Ninject.Extensions.Factory that allows you to generate Abstract Factory implementation on fly based on interface

Kernel configuration

var kernel = new StandardKernel();

// wire concrete implementation to abstraction/interface
kernel.Bind<IJob>().To<JobImpl1>()
    .NamedLikeFactoryMethod<IJob, IJobFactory>(f => f.GetJob());

// configure IJobFactory to be Abstract Factory
// that will include kernel and act according to kernel configuration    
kernel.Bind<IJobFactory>().ToFactory();

Resolve Abstract Factory at runtime using kernel

// get an instance of Abstract Factory
var abstractFactory = kernel.Get<IJobFactory>();

// resolve dependency using Abstract Factory
var job = abstractFactory.GetJob()

Abstract Factory interface

public interface IJobFactory
{
    IJobFactory GetJob();
}