NinjectMVC3: Dependency Injection in 30 seconds or less

I'm frequently baffled by the hoops one must go through in order to setup things like dependency injection in a web app. While browsing through Ayende's Raccoon Blog source code, I noticed he avoided using IoC and instead created a helper class to manage store/session lifetimes. Seemed like more work than I wanted to do.
Instead of spending time avoid the IoC setup pain, I took Ninject.MVC3 for a test drive. It went something like:
  1. Use Nuget to get Ninject.MVC3
  2. Edit RegisterServices -- the Nuget package conveniently adds some code in the App_Start folder so you don't have to worry about the boiler plate.  In this case, I wanted to pass a controller an instance of IDocumentStore for RavenDB:
Code Snippet
  1. private static void RegisterServices(IKernel kernel)
  2.         {
  3.             kernel
  4.                 .Bind()
  5.                 .To()
  6.                 .InSingletonScope()
  7.                 .WithPropertyValue("Url", "http://localhost:8080")
  8.                 .OnActivation(store => store.Initialize());
  9.         }
 
3. Use IDocumentStore in my controllers.
  
Code Snippet
  1. IDocumentStore store;
  2.  
  3. public AdminController(IDocumentStore store)
  4. {
  5.     this.store = store;
  6. }

 

Pretty slick.

1comment