使用Ninject和全局筛选器的依赖项注入:IAuthorizationFilter



我使用安装在App_Start文件夹中的standart NinjectMVC3引导程序。

我的应用程序类看起来像:

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。

但是我的代码不起作用。谢谢

从您的代码中还不太清楚您在哪里配置内核。这应该在~/App_Start/NinjectMVC3.cs:的RegisterServices方法中完成

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

当你安装Ninject.MVC3NuGet包时,这个方法的主体将是空的,你应该在这里直接配置依赖项或定义你将用这个方法导入的Ninject模块:

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

您定义自定义模块的位置:

public class MyModule : NinjectModule
{
    public override void Load()
    {
        this.Bind<IAccountsRepository>().To<AccountsRepository>();
        this.BindFilter<GlobalAuthFilter>(FilterScope.Global, 0);
    }
}

相关内容

  • 没有找到相关文章

最新更新