Ninject and MVC3: Dependency injection to action filters

Rob Stevenson-Leggett picture Rob Stevenson-Leggett · Feb 22, 2011 · Viewed 11.4k times · Source

I've found loads of inconclusive articles and questions on how to do property injection on an ActionFilter in ASP.NET MVC3 using Ninject.

Could someone give me a clear example please?

Here's my custom auth attribute.

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    [Inject]
    public IService Service { get; set; }

    [Inject]
    public IAuthenticationHelper AuthenticationHelper { get; set; }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
         //My custom code
    }
 }

I am using the WebActivator to set up Ninject

[assembly: WebActivator.PreApplicationStartMethod(typeof(MyProject.Web.AppStart_NinjectMvc3), "Start")]

 namespace MyProject.Web {

   public static class AppStart_NinjectMvc3 {
        public static void RegisterServices(IKernel kernel) {

           //Binding things
    }

    public static void Start() {
        // Create Ninject DI Kernel 
        IKernel kernel = new StandardKernel();

        // Register services with our Ninject DI Container
        RegisterServices(kernel);

        // Tell ASP.NET MVC 3 to use our Ninject DI Container 
        DependencyResolver.SetResolver(new NinjectServiceLocator(kernel));
    }

  }
}

My service and helper are never injected. What do I need to change?

Answer

Remo Gloor picture Remo Gloor · Feb 22, 2011

In my opinion there is a better solution than using filter attributes. See my blogposts about an alternative way of declaring filters using Ninject. It does not require property injection and uses constructor injection instead:

http://www.planetgeek.ch/2010/11/13/official-ninject-mvc-extension-gets-support-for-mvc3/ http://www.planetgeek.ch/2011/02/22/ninject-mvc3-and-ninject-web-mvc3-merged-to-one-package/