asp.net mvc 的 Ninject 和 Filter 属性的依赖注入

发布于 2024-11-12 05:28:00 字数 737 浏览 0 评论 0 原文

我正在为 asp.net mvc 3 编写一个自定义授权过滤器。我需要将用户服务注入到类中,但我不知道如何执行此操作。

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();
    }
}

我正在使用 ninject 进行依赖注入。我不想使用工厂或服务定位器模式。

我的绑定在 global.acsx 中如下所示:

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

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>();
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

预谋 2024-11-19 05:28:00

请参阅此答案:自定义授权 MVC 3 和 Ninject IoC

如果你想使用构造函数注入,那么你需要创建一个属性和一个过滤器。

/// 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" } });
          }
      }
}

绑定:

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

控制器:

[MyAuthorizeAttribute]
public class YourController : Controller
{
    // ...
}

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
{
    // ...
}
指尖凝香 2024-11-19 05:28:00

强烈推荐B Z的回答不要使用[Inject]

我使用了[Inject],例如Darin Dimitrov 说 是有可能的,它实际上在与 .InRequestScope 结合的高负载、高争用情况下导致了线程问题。

B Z 的方式也是 Wiki 上的方式,我在很多地方都看到雷莫·格洛尔 (Ninject 作者)说这是正确的方法,例如 https://github.com/ninject/ninject.web.mvc/wiki/Filter-configurations

在这里对 [Inject] 答案投反对票,因为说真的,你会被烧伤(如果你没有事先正确加载测试,可能会在生产中!)。

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

生活了然无味 2024-11-19 05:28:00

我找到了一个简单的解决方案,适用于 Ninject 不处理构造的任何场合:

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

实际上,这正是我在自定义 AuthorizeAttribute 中使用的解决方案。比实现单独的 FilterAttribute 容易得多。

I found a simple solution for any occasion where construction is not handled by 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.

蓝咒 2024-11-19 05:28:00

一种方法是使用属性注入并使用 [Inject] 属性装饰属性:

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

    private string[] roles;
  
    ...
}

构造函数注入不能很好地处理属性,因为您将无法再用它们装饰控制器/操作。您只能在 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;
    }
  
    ...
}

然后:

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

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

BindFilter<> 扩展方法在 Ninject.Web.Mvc.FilterBindingSyntax 命名空间中定义因此,在内核上调用它之前,请确保已将其纳入范围。

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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文