1

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.

Adam Levitt
  • 10,316
  • 26
  • 84
  • 145

1 Answers1

2

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();
}
Akim
  • 8,469
  • 2
  • 31
  • 49
  • This feels like it's on the right track, but what I need is to be able to have multiple implementations of the same interface in the same environment. An example would be where I need multiple implementations of an IVehicle interface (truck, car, motorcycle, etc.) – Adam Levitt Dec 24 '12 at 18:03
  • Add new methods signatures to _Abstract Factory_ and use _NamedLikeFactoryMethod_ to configure mapping – Akim Dec 25 '12 at 09:26