Autofac Multiple Lifetime Scopes with single Container


April 2019


22 time


I'm trying to figure out a work around for using multiple lifetimes with a single Container.

The problem is related to InstancePerRequest() implementation.

There is an application based on WebAPI with custom WebHandler, so Autofac can not define whether the LifetimeScope is initialized or disposed. So i can not use basic InstancePerRequest(). I decided to implement semi-custom InstancePerRequest() according to Autofac documentation

The Autofac registration looks like this:

private static IContainer Container;

private static void RegisterServices()
    var builder = new ContainerBuilder();
    builder.Register((c, p) => new CustomClass(p.Named<List<int>>("codes"), p.Named<User>("user")))

    Container = builder.Build();

public static ILifetimeScope BeginLifetimeScope()
    return Container.BeginLifetimeScope(new[] { MatchingScopeLifetimeTags.RequestLifetimeScopeTag });

MatchingScopeLifetimeTags.RequestLifetimeScopeTag is required in Autofac Custom per-request semantics according to this article (point 2)

So i manually create LifetimeScope:

... // AutofacHelper.BeginLifetimeScope() is implemented above
using (var lifetimeScope = AutofacHelper.BeginLifetimeScope())
    result = InvokeRequest(request.Api, context);

The problem is that there are as many LifetimeScope's as requests. And the scope i need begins far away from the code, where i need to access it. I need to have access to the current scope from anywhere.

I guess i have to tag every LifetimeScope with HttpContext.Current and that would be unique enough to define which scope i need to use.

But how do i do that? Implementing BeginLifetimeScope() with parameter new[] { MatchingScopeLifetimeTags.RequestLifetimeScopeTag, HttpContext.Current } leads to exception as it can not find requested scope.

Is there a way to define which scope is being used in current request? Using my custom unique tag for example? ILifetimeScope has implementation for parent scopes only. Is there a reason for not implementing child scopes so i could take them according to HttpContext.Current?

Any ideas?


0 answers