Created
January 21, 2012 03:36
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NinjectFactory : IFactory | |
{ | |
private readonly IKernel kernel; | |
public Factory(IKernel kernel) | |
{ | |
this.kernel = kernel; | |
} | |
public T Get<T>() | |
{ | |
return kernel.Get<T>(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IFactory | |
{ | |
T Get<T>(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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