【问题标题】:Creating global Ninject kernel in Global.asax在 Global.asax 中创建全局 Ninject 内核
【发布时间】:2016-05-23 08:51:02
【问题描述】:

我想在 Application_BeginRequest() 方法中访问 Ninject Kernel。所以我在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() 方法中为空。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多