Dependency Injection with Ninject and Global Filter: IAuthorizationFilter

杀马特。学长 韩版系。学妹 提交于 2019-12-24 14:58:19

问题


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.


回答1:


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:

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

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:

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

where you have defined the custom module:

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


来源:https://stackoverflow.com/questions/9079228/dependency-injection-with-ninject-and-global-filter-iauthorizationfilter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!