-1

在我的 WebApiApplication 中,我试图初始化一个IContainerin 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.

我在这里做错了什么?

4

1 回答 1

0

您需要添加static以便容器在应用程序的整个生命周期内都存在

private static IContainer _container
于 2018-06-12T21:19:37.273 回答