Yes, StructureMap uses Nested Containers under the hood when plugged into Asp.Net Core framework as a DI container of your choice.

To prove that, have a look into the source code of DependencyInjection NuGet package which serves as an integration package. Here you view the code from the snippet below.

internal sealed class StructureMapServiceScopeFactory : IServiceScopeFactory
{
    public IServiceScope CreateScope()
    {
        return new StructureMapServiceScope(Container.GetNestedContainer());
    }

    // ... details omitted
}

Why is this important?

Using Nested container per request over HttpContext based lifecycles is based on the StructureMap docs a better, lighterweight way to scope services to an HTTP request without coupling your code to what will soon be legacy ASP.Net runtime code.

There are a few things to be aware of, however.

Lifecycle rule changes

With a use of Nested Containers, lifecycle rules changes:

  • Transient - a new object is created for each Http request (Nested container). This differs to the behavior of Transient lifecycle rule in the root cotainer where a new object is created for each container request (i.e. Container.GetInstance())
  • Instances scoped to anything but Transient or AlwaysUnique - are resolved as normal, but through the parent container. These currently are ContainerScoped, ThreadLocal and Singleton.

More description can be viewed at StructureMap docs lifecycle page.

Disposing services

Disposing a nested container will also dispose all objects created with the default Transient lifecycle by the nested container that implement the IDisposable interface.

When working outside of a nested container and especially when using Transient lifecycle, make sure to read StructureMap disposing page. What object gets disposed changes with version 4 of StructureMap.

Resources