具有Ninject和Filter屬性的asp.net mvc的依賴注入

[英]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.

我正在為asp.net mvc 3編寫一個自定義授權過濾器。我需要向類中注入一個userservice,但是我不知道怎么做。

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.

我在使用ninject進行依賴注入。我不想使用工廠或服務定位器模式。

My bindings look like this in the global.acsx:

我的綁定在global.acsx上是這樣的:

    internal class SiteModule : NinjectModule
    {
        public override void Load()
        {
            Bind<IUserService>().To<UserService>();
        }
    }

4 个解决方案

#1


78  

See this answer:

看到這個回答:

Custom Authorization MVC 3 and Ninject IoC

自定義授權MVC 3和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
{

}

HTH...

HTH……

#2


11  

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

我強烈推薦B Z的答案。不使用(注入)!

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.

我使用了像Darin Dimitrov這樣的[注入],這是可能的,它實際上是在高負載、高爭用情況和. 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

B Z的方式也是Wiki上的內容,我在很多地方見過Remo Gloor (Ninject作者)說這是正確的方式

https://github.com/ninject/ninject.web.mvc/wiki/Filter-configurations

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 prior!)

Downvote[注入]答案在這里,因為嚴重的你會被燒傷(可能在生產中如果你沒有正確的負荷測試!)

#3


8  

On way would be to use a property injection and decorate the property with the [Inject] attribute:

在方法上,將使用屬性注入並使用[注入]屬性來裝飾屬性:

public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
    [Inject]
    public IUserService UserService { get; set; }

    private string[] roles;

    ...
}

Constructor injection doesn't work well with attributes as you will no longer be able to decorate controllers/actions with them. You could only use constructor injection with the filter binding syntax in NInject:

構造函數注入不能很好地處理屬性,因為您將不再能夠使用它們來修飾控制器/操作。您只能在NInject中使用帶有過濾器綁定語法的構造函數注入:

public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
    private readonly IUserService userService;

    private string[] roles;

    public AuthorizeAttribute(IUserService userService, params string[] roles)
    {
        this.userService = userService;
        this.roles = roles;
    }

    ...
}

and then:

然后:

internal class SiteModule : Ninject.Modules.NinjectModule
{
    public override void Load()
    {
        Bind<IUserService>().To<UserService>();

        this.BindFilter<AuthorizeAttribute>(FilterScope.Controller, 0)
            .WhenControllerType<AdminController>();
    }
}

The BindFilter<> extension method is defined in the Ninject.Web.Mvc.FilterBindingSyntax namespace so make sure you have brought that into scope before calling it on a kernel.

BindFilter<>擴展方法在ninjet . web . mvc中定義。FilterBindingSyntax命名空間,所以請確保在在內核上調用它之前已經將其引入范圍。

#4


6  

I found a simple solution for any occasion where construction is not handled by Ninject:

我找到了一個簡單的解決方案,適用於任何情況下,建設不是由Ninject處理的:

var session = (IMyUserService)DependencyResolver.Current.GetService(typeof (IMyUserService));

Actually this is exactly what I am using with my custom AuthorizeAttribute. Much easier than having to implement a separate FilterAttribute.

實際上,這正是我使用自定義AuthorizeAttribute時使用的。要比實現單獨的FilterAttribute容易得多。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/05/31/a4e8778b705327a0cf29da6328ef968a.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com