Ninject Module for ASP.NET MVC Controller Bindings

An entry about asp.net | asp.net mvc | inversion of control Publication date 25. August 2008 11:00

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!

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.


Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS