在Application_Start中初始化StructureMap容器​​,但它在Application_BeginRequest中为null

时间:2018-06-11 21:40:22

标签: c# ioc-container structuremap4

在我的WebApiApplication中,我尝试初始化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()开头之间的某处,_container字段变为null

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

您需要添加static,以便容器适用于lifetime of the application

private static IContainer _container