使用 Ninject 和全局过滤器进行依赖注入:IAuthorizationFilter
我使用安装在 App_Start 文件夹中的标准 NinjectMVC3 Bootstrapper。
我的应用程序类如下所示:
public class MvcApplication : HttpApplication
{
static void RegisterRoutes(RouteCollection routes)
{
// ... routes here ...
}
public void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// empty
}
}
我在 NinjectMVC3 中仅注册了以下出价规则:
Bind<IAccountsRepository>().To<AccountsRepository>();
this.BindFilter<GlobalAuthFilter>(FilterScope.Global, 0);
我的全局过滤器:
public class GlobalAuthFilter : IAuthorizationFilter
{
readonly IAccountsRepository _accountsRepository;
public GlobalAuthFilter(IAccountsRepository accountsRepository)
{
_accountsRepository = accountsRepository;
}
public void OnAuthorization(AuthorizationContext context)
{
// Code here never reached. Why? What's wrong?
}
}
我的应用程序中有任何控制器。我想为每个控制器的每个操作调用调用 OnAuthorization。
但我的代码不起作用。谢谢。
I use standart NinjectMVC3 Bootstrapper installed in the App_Start folder.
My application class looks like:
public class MvcApplication : HttpApplication
{
static void RegisterRoutes(RouteCollection routes)
{
// ... routes here ...
}
public void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// empty
}
}
I have only following bidding rules registed in NinjectMVC3:
Bind<IAccountsRepository>().To<AccountsRepository>();
this.BindFilter<GlobalAuthFilter>(FilterScope.Global, 0);
And my global filter:
public class GlobalAuthFilter : IAuthorizationFilter
{
readonly IAccountsRepository _accountsRepository;
public GlobalAuthFilter(IAccountsRepository accountsRepository)
{
_accountsRepository = accountsRepository;
}
public void OnAuthorization(AuthorizationContext context)
{
// Code here never reached. Why? What's wrong?
}
}
There are any controllers in my application. And I want to invoke OnAuthorization for every action calls for every controllers.
But my code dosn't work. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从您的代码中并不清楚您在哪里更具体地配置内核。这应该在
~/App_Start/NinjectMVC3.cs
的RegisterServices
方法中完成:当您安装
Ninject.MVC3
NuGet 包的主体时此方法将为空,您应该直接配置依赖项或定义要在此方法中导入的 Ninject 模块:您定义了自定义模块的位置:
It's not quite clear from your code where more specifically are you configuring your kernel. This should be done in the
RegisterServices
method of~/App_Start/NinjectMVC3.cs
:When you install the
Ninject.MVC3
NuGet package the body of this method will be empty and it is where you should either directly configure dependencies or define Ninject modules that you would import in this method:where you have defined the custom module: