在Global.asax中创建全局Ninject内核

时间:2016-02-12 09:10:10

标签: c# asp.net-web-api ninject ninject.web.mvc

我想在 Application_BeginRequest()方法中访问Ninject内核。所以我在HttpContext.Current.Items中设置了Ker nel。

   public class WebApiApplication : HttpApplication
    {
        public IKernel Kernel
        {
            get { return (IKernel) HttpContext.Current.Items["Context"]; }
            set { HttpContext.Current.Items["Context"] = value; }
        }

        protected void Application_Start()
        {
            .....

            Kernel = new StandardKernel();

            GlobalConfiguration.Configuration.DependencyResolver = 
                         new NinjectDependencyResolver(Kernel);

            Debug.WriteLine("Application started with kernel: {0}", Kernel);
        }

        protected void Application_BeginRequest()
        {
            Debug.WriteLine("Application begin request with kernel: {0}", Kernel);
        }

我启动应用程序但是Application_BeginRequest()方法中的内核对象为空。

1 个答案:

答案 0 :(得分:0)

HttpContext.Current.Items是特定于请求的。因此,它们会针对每个请求重新创建。为了能够访问请求中的Kernel,您需要在Application_BeginRequest中基于每个请求进行设置:

public class WebApiApplication : HttpApplication
{
    private static Kernel globalKernel;

    public static IKernel Kernel
    {
        get { return (IKernel) HttpContext.Current.Items["Context"]; }
        set { HttpContext.Current.Items["Context"] = value; }
    }

    protected void Application_Start()
    {
        .....

        globalKernel = new StandardKernel();

        GlobalConfiguration.Configuration.DependencyResolver = 
                     new NinjectDependencyResolver(globalKernel);

        Debug.WriteLine("Application started with kernel: {0}", globalKernel);
    }

    protected void Application_BeginRequest()
    {
        // This adds the Kernel to the items collection that is specific to the request
        Kernel = globalKernel;
        Debug.WriteLine("Application begin request with kernel: {0}", Kernel);
    }