asp.net mvc 的 Ninject 和 Filter 属性的依赖注入
我正在为 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>();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请参阅此答案:自定义授权 MVC 3 和 Ninject IoC
如果你想使用构造函数注入,那么你需要创建一个属性和一个过滤器。
绑定:
控制器:
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.
Binding:
Controller:
我强烈推荐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!).我找到了一个简单的解决方案,适用于 Ninject 不处理构造的任何场合:
实际上,这正是我在自定义
AuthorizeAttribute
中使用的解决方案。比实现单独的 FilterAttribute 容易得多。I found a simple solution for any occasion where construction is not handled by Ninject:
Actually this is exactly what I am using with my custom
AuthorizeAttribute
. Much easier than having to implement a separateFilterAttribute
.一种方法是使用属性注入并使用
[Inject]
属性装饰属性:构造函数注入不能很好地处理属性,因为您将无法再用它们装饰控制器/操作。您只能在 Ninject 中使用带有过滤器绑定语法的构造函数注入:
然后:
BindFilter<>
扩展方法在Ninject.Web.Mvc.FilterBindingSyntax
命名空间中定义因此,在内核上调用它之前,请确保已将其纳入范围。On way would be to use a property injection and decorate the property with the
[Inject]
attribute: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:
and then:
The
BindFilter<>
extension method is defined in theNinject.Web.Mvc.FilterBindingSyntax
namespace so make sure you have brought that into scope before calling it on a kernel.