Accessing ninject kernel in Application_Start

半城伤御伤魂 提交于 2019-12-03 10:20:00

MVC 3 introduces the DependencyResolver which is populated into a singleton, and the Ninject extension supports it. You could use that in your MvcApplication class if you need it:

protected void Application_Start()
{
    // ...
    var logger = DependencyResolver.Current.GetService<ILogger>();
}

Now I should point out that it is unnecessary to do this with action filters. In Ninject.MVC3 you are supposed to use the BindFilter syntax, like so:

// Declare empty attribute
public class MyFilterAttribute : FilterAttribute { }

// Dependency module
public class MyModule : NinjectModule
{
    public override void Load()
    {
        // Other bindings
        // ...
        this.BindFilter<MyActionFilter>(FilterScope.Action, 1)
            .WhenControllerHas<MyFilterAttribute>();
    }
}

Note that you have to use this because BindFilter is an extension method, and you also have to reference the Ninject.Web.Mvc.FilterBindingSyntax namespace.

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