Reputation: 10476
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.
Upvotes: 1
Views: 1166
Reputation: 8669
There is a separate extension Ninject.Extensions.Factory that allows you to generate Abstract Factory implementation on fly based on interface
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();
// get an instance of Abstract Factory
var abstractFactory = kernel.Get<IJobFactory>();
// resolve dependency using Abstract Factory
var job = abstractFactory.GetJob()
public interface IJobFactory
{
IJobFactory GetJob();
}
Upvotes: 2