Archive

Posts Tagged ‘IOC’

Loosely couple ninject kernel in MVC applications

27/07/2011 Leave a comment

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)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Gallery", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();

AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
protected override IKernel CreateKernel()
      {
var kernel = new StandardKernel();
kernel.Load(AppDomain.CurrentDomain.GetAssemblies());
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()
{
Bind<IGalleryRepository>().To<GalleryRepository>();
}
}
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.
Advertisements
Categories: .Net, MVC Tags: , , ,