Setting up Ninject for use with ASP.NET MVC is dead easy; just use the integration API included in the MvcContrib project. However, registering all your controllers by hand can be tedious. Writing a custom module that automatically loads all the controllers in a given assembly is straight-forward, however:
public class ControllerModule : StandardModule
{
private readonly Assembly _assembly;
public ControllerModule(Assembly assembly)
{
_assembly = assembly;
}
public override void Load()
{
Type controllerType = typeof (IController);
// find all types in the assembly that implement the IController interface
foreach(Type type in _assembly.GetTypes())
{
if(controllerType.IsAssignableFrom(type))
{
string controllerName = type.Name;
// strip the "Controller" suffix from name
int cutIndex = controllerName.LastIndexOf("Controller");
if(cutIndex > 0) controllerName = controllerName.Substring(0, cutIndex);
// register controller binding
Bind<IController>().To(type).Only(When.Context.Variable("controllerName").EqualTo(controllerName));
}
}
}
}
And then your Global.asax will look like this:
public class GlobalApplication : HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// *snip* route registration
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
InitializeNinject();
}
public void InitializeNinject()
{
NinjectKernel.Initialize(new ControllerModule(Assembly.GetExecutingAssembly()));
ControllerBuilder.Current.SetControllerFactory(typeof(NinjectControllerFactory));
}
}
Happy days!