Search code examples
c#ioc-containerstructuremap4

Initializing a StructureMap container in Application_Start but it's null in Application_BeginRequest


In my WebApiApplication I'm trying to initialize an IContainer in Application_Start and store it in _container field:

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

When debugging, somewhere between the close of Application_Start() and the beginning of Application_BeginRequest(), the _container field becomes null.

What am I doing wrong here?


Solution

  • You need add static so that the container lives for the lifetime of the application.

    private static IContainer _container