1

我使用安装在 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。

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

4

1 回答 1

4

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);
    }
}
于 2012-01-31T12:17:12.693 回答