I’m trying to set up Ninject for the first time. I’ve got an IRepository interface, and a Repository implementation. I’m using ASP.NET MVC, and I’m trying to inject the implementation like so:
public class HomeController : Controller
{
[Inject] public IRepository<BlogPost> _repo { get; set; }
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
var b = new BlogPost
{
Title = "My First Blog Post!",
PostedDate = DateTime.Now,
Content = "Some text"
};
_repo.Insert(b);
return View();
}
// ... etc
}
And here’s Global.asax:
public class MvcApplication : NinjectHttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected override void OnApplicationStarted()
{
RegisterRoutes(RouteTable.Routes);
}
protected override IKernel CreateKernel()
{
IKernel kernel = new StandardKernel(new BaseModule());
return (kernel);
}
}
And here’s the BaseModule class:
public class BaseModule : StandardModule
{
public override void Load()
{
Bind<IRepository<BlogPost>>().To<Repository<BlogPost>>();
}
}
When I browse to the Index() action, though, I get “Object reference not set to an instance of an object” when trying to use _repo.Insert(b). What am I leaving out?
Ninject 1.0 did not have MVC support out of the box. There are various ways of using MVC with Ninject 1.0 scattered around the web.
I’d recommend getting the latest code from the Ninject trunk, which includes MVC support. Then use the following as a starting point for your application:
There are a few things to highlight versus your original implementation…
implementations names
NinjectHttpApplication – one in
Ninject.Framework.Web and one in
Ninject.Framework.Mvc. You appear to
be using the former as the later
contains a protected RegisterRoutes()
method.