正在 Application_Start 中初始化一个 StructureMap 容器,但它在 Application_BeginRequest 中为空
Initializing a StructureMap container in Application_Start but it's null in Application_BeginRequest
在我的 WebApiApplication 中,我试图在 Application_Start
中初始化一个 IContainer
并将其存储在 _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()
开始之间的某处,_container
字段变为 null
。
我做错了什么?
您需要添加 static
以便容器可以使用 lifetime of the application。
private static IContainer _container
在我的 WebApiApplication 中,我试图在 Application_Start
中初始化一个 IContainer
并将其存储在 _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()
开始之间的某处,_container
字段变为 null
。
我做错了什么?
您需要添加 static
以便容器可以使用 lifetime of the application。
private static IContainer _container