Home > .Net, MVC > Loosely couple ninject kernel in MVC applications

Loosely couple ninject kernel in MVC applications

I’m currently working on a hobby project “a photosite”, where I’m using MVC 3 with Entity Framwork 4 and Ninject IOC container. Maybe I overdid the decoupling of the Ninject kernel for this project, but I was fun to do and I gave material for this post :). The goal was to build a MVC project where the repository implementation was placed in separate project together with ninject binding.

So here is the repository Interaface:

public interface IGalleryRepository
   IEnumerable<Gallery> All { get; }

And here is the concrete implementation for the interface

public class GalleryRepository : IGalleryRepository
   PhotoSiteContext context = new PhotoSiteContext();
   public IEnumerable<Gallery> All
    get { return context.Galleries; }

Now we need to alter the global.asax file with the following.

public class MvcApplication : NinjectHttpApplication
   public static void RegisterGlobalFilters(GlobalFilterCollection filters)
     filters.Add(new HandleErrorAttribute());
public static void RegisterRoutes(RouteCollection routes)
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Gallery", action = "Index", id = UrlParameter.Optional } // Parameter defaults
protected override void OnApplicationStarted()

protected override IKernel CreateKernel()
var kernel = new StandardKernel();
return kernel;

By loading the kernel this way Ninject will looke through all dll’s in the bin folder of MVC project “main project” and load all assemblies which inherit from the NinjectModul class.

Now we cant in same project as the implementation of the inteface make a new class which derives from Ninject modul. The class should look like this.

public class SqlCompactNinjectModule : NinjectModule
public override void Load()
With this setup it would be possible to switch the gallery implementation simply by adding a new dll with a NinjectModule and a concrete implementation of the IgalleriInterface.
I hope you find this usefull.
Categories: .Net, MVC Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: