2016-02-12 64 views
0

我想訪問Application_BeginRequest()方法中的Ninject內核。所以我在HttpContext.Current.Items中設置了Kerne。在Global.asax中創建全局Ninject內核

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()方法無效的到來。

回答

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