Skip to content

Instantly share code, notes, and snippets.

@greggnakamura
Created October 11, 2012 04:18
Show Gist options
  • Save greggnakamura/3870135 to your computer and use it in GitHub Desktop.
Save greggnakamura/3870135 to your computer and use it in GitHub Desktop.
MVC: Bind null reference when attempting to register the IProductsRepository with the DI container
using Ninject;
using Ninject.Modules;
using SportsStore.Domain.Abstract;
using SportsStore.Domain.Concrete;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace SportsStore.WebUI.Infrastructure
{
/// <summary>
/// Stop MVC from instantiating controller classes directly, & make it request them from your DI container
/// This will allow the DI container to resolve any dependencies those controllers may have.
/// </summary>
public class NinjectControllerFactory : DefaultControllerFactory
{
// A Ninject "kernel" is the thing that can supply object instances
private IKernel kernel = new StandardKernel(new SportsStoreServices());
// ASP.NET MVC calls this to get the controller for each request
protected override IController GetControllerInstance(RequestContext context, Type controllerType)
{
if (controllerType == null)
return null;
return (IController)kernel.Get(controllerType);
}
// Configure how abstract service types are mapped to concrete implementations
private class SportsStoreServices : NinjectModule
{
public override void Load()
{
Bind<IProductsRepository>()
.To<SqlProductsRepository>()
.WithConstructorArgument("connectionString",
ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString
);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment