我使用安装在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。
但我的代码不起作用。感谢。
答案 0 :(得分:4)
从您的代码中可以更明确地了解内核的具体配置。这应该在RegisterServices
的{{1}}方法中完成:
~/App_Start/NinjectMVC3.cs
当您安装/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IAccountsRepository>().To<AccountsRepository>();
kernel.BindFilter<GlobalAuthFilter>(FilterScope.Global, 0);
}
NuGet包时,此方法的主体将为空,您应该直接配置依赖项或定义要在此方法中导入的Ninject模块:
Ninject.MVC3
您已定义自定义模块:
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Load(new MyModule());
}