Skip to content

Instantly share code, notes, and snippets.

@bfriesen
Created January 21, 2012 03:36
Show Gist options
  • Save bfriesen/1651134 to your computer and use it in GitHub Desktop.
Save bfriesen/1651134 to your computer and use it in GitHub Desktop.
Yo dawg, I heard you like dependency injection, so I injected a ninject factory that uses a ninject kernel into your controller using the same ninject kernel so you can inject multiple dependencies without having to inject each one individually.
public class NinjectFactory : IFactory
{
private readonly IKernel kernel;
public Factory(IKernel kernel)
{
this.kernel = kernel;
}
public T Get<T>()
{
return kernel.Get<T>();
}
}
public interface IFactory
{
T Get<T>();
}
public class MyController : Controller
{
private readonly IFactory factory;
public MyController(IFactory factory)
{
this.factory = factory;
}
public ActionResult DoSomething()
{
// Passing each of these dependencies into the constructor (plus any that are used by other methods) gets to be a pain, especially during testing.
var customerRepository = factory.Get<ICustomerRepository>();
var orderRepository = factory.Get<IOrderRepository>();
var taxCalculator = factory.Get<ITaxCalculator>();
var zipCodeService = factory.Get<IZipCodeService>();
// Do stuff with the repositories, the tax calculator, and the zip code service in order to determine the result
return theResult;
}
}
public class MyWebApplication : NinjectHttpApplication
{
public override IKernel CreateKernel()
{
var kernel = new StandardKernel();
// Bind IFactory to NinjectFactory using kernel, passing kernel itself into the NinjectFactory's constructor.
kernel.Bind<IFactory>().To<NinjectFactory>().InSingletonScope().WithConstructorArgument("kernel", kernel);
// Binding the IKernel to itself is left as an exercise to the reader...
return kernel;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment