Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject and MVC3: Dependency injection to action filters

Tags:

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?

like image 504
Rob Stevenson-Leggett Avatar asked Feb 22 '11 12:02

Rob Stevenson-Leggett


People also ask

What is ninject dependency injection?

Ninject is a lightweight dependency injection framework for . NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner.

What is dependency injection in MVC with example?

The Dependency Injection pattern is a particular implementation of Inversion of Control. Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).

What is a ninject module?

The Ninject modules are the tools used to register the various types with the IoC container. The advantage is that these modules are then kept in their own classes. This allows you to put different tiers/services in their own modules.


2 Answers

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/

like image 164
Remo Gloor Avatar answered Nov 03 '22 21:11

Remo Gloor


Here's how you could proceed:

public class MvcApplication : Ninject.Web.Mvc.NinjectHttpApplication
{
    private class MyModule : NinjectModule
    {
        public override void Load()
        {
            Bind<IService>().To<ServiceImpl>();
            Bind<IAuthenticationHelper>().To<AuthenticationHelperImpl>();
        }
    }

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

    protected override void OnApplicationStarted()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

    protected override IKernel CreateKernel()
    {
        var modules = new INinjectModule[] {
            new MyModule()
        };
        var kernel = new StandardKernel(modules);
        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
        return kernel;        
    }
}

and then you could have your custom authorize attribute:

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

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

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
    }
}

and a controller action decorated with it:

[CustomAuthorize]
public ActionResult Index()
{
    return View();
}

and the dependencies should be injected.

like image 40
Darin Dimitrov Avatar answered Nov 03 '22 20:11

Darin Dimitrov