代码之家  ›  专栏  ›  技术社区  ›  Scott Baker

在应用程序启动中初始化structuremap容器,但在应用程序beginrequest中为空

  •  -1
  • Scott Baker  · 技术社区  · 6 年前

    在我的webapi应用程序中,我试图初始化 IContainer 在里面 Application_Start 储存在 _container 领域:

    public class WebApiApplication : System.Web.HttpApplication
    {
        private IContainer _container;
    
        public IContainer Container
        {
            get => (IContainer)HttpContext.Current.Items[nameof(Container)];
            set => HttpContext.Current.Items[nameof(Container)] = value;
        }
    
        protected void Application_Start()
        {
            _container = new Container(_ => _.Scan(scan =>
            {
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
                scan.With(new ControllerConvention());
            }));
    
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            DependencyResolver.SetResolver(new StructureMapDependencyResolver(() => 
                Container ?? _container.GetNestedContainer()));
    
    
        }
    
        public void Application_BeginRequest() =>
            Container = _container.GetNestedContainer();
    
        public void Application_EndRequest()
        {
            Container.Dispose();
            Container = null;
        }
    }
    

    在调试时,介于 Application_Start() 以及 Application_BeginRequest() , the 容器,容器 场变成 null .

    我在这里做错什么了?

    1 回复  |  直到 6 年前
        1
  •  0
  •   mjwills Myles McDonnell    6 年前

    你需要添加 static 使容器为 lifetime of the application .

    private static IContainer _container