Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection with Ninject and Filter attribute for asp.net mvc

I'm writing a custom Authorization Filter for asp.net mvc 3. I need to inject a userservice into the class but I have no idea how to do this.

public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter {     private IUserService userService;     private string[] roles;      public AuthorizeAttribute(params string[] roles)     {         this.roles = roles;     }      public void OnAuthorization(AuthorizationContext filterContext)     {         throw new NotImplementedException();     } } 

I'm using ninject for dependency injection. I do not want to use a Factory or service locator pattern.

My bindings look like this in the global.acsx:

    internal class SiteModule : NinjectModule     {         public override void Load()         {             Bind<IUserService>().To<UserService>();         }     } 
like image 400
Shawn Mclean Avatar asked May 31 '11 20:05

Shawn Mclean


People also ask

What is NInject dependency injection?

NInject is a popular IOC container that can be used to inject dependencies in your WebAPI controllers easily. IDG. Dependency injection is a software design pattern that helps you to build pluggable implementations in your application using loosely coupled, testable components.

What is dependency injection in asp net 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 dependency injection in .NET core MVC?

ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.


2 Answers

See this answer: Custom Authorization MVC 3 and Ninject IoC

If you want to use constructor injection then you need to create an attribute and a filter.

/// Marker attribute public class MyAuthorizeAttribute : FilterAttribute { }  /// Filter public class MyAuthorizeFilter : IAuthorizationFilter {       private readonly IUserService _userService;       public MyAuthorizeFilter(IUserService userService)       {           _userService = userService;       }        public void OnAuthorization(AuthorizationContext filterContext)       {           var validUser = _userService.CheckIsValid();            if (!validUser)           {               filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "action", "AccessDenied" }, { "controller", "Error" } });           }       } } 

Binding:

this.BindFilter<MyAuthorizeFilter>(System.Web.Mvc.FilterScope.Controller, 0).WhenControllerHas<MyAuthorizeAttribute>(); 

Controller:

[MyAuthorizeAttribute] public class YourController : Controller {     // ... } 
like image 86
B Z Avatar answered Sep 20 '22 08:09

B Z


I would highly recommend B Z's answer. DO NOT use [Inject]!

I used an [Inject] like Darin Dimitrov said was possible and it actually caused threading issues under high load, high contention situations in conjunction with .InRequestScope.

B Z's way is also what is on the Wiki and I have seen many places where Remo Gloor (Ninject author) says this is the correct way to do it, e.g. https://github.com/ninject/ninject.web.mvc/wiki/Filter-configurations.

Downvote [Inject] answers in here because seriously you will get burned (probably in production if you don't load test properly beforehand!).

like image 32
John Culviner Avatar answered Sep 20 '22 08:09

John Culviner