I have an ASP.NET Web API project using Autofac for dependency injection.
I register a factory for creating ICommandExecutor based on an enum:
builder.Register<Func<CommandType, ICommandExecutor>>(c =>
{
var context = c.Resolve<IComponentContext>();
return commandType => context.ResolveNamed<ICommandExecutor>(commandType.ToString());
})
.SingleInstance();
My executors are registered as keyed singletons:
builder.RegisterType<QueryExecutor>()
.Named<ICommandExecutor>(CommandType.Query.ToString())
.SingleInstance();
builder.RegisterType<IngestExecutor>()
.Named<ICommandExecutor>(CommandType.Ingest.ToString())
.SingleInstance();
When my Web API controllers call into this factory during a request, things work most of the time.
But intermittently, calling the function throws an exception:
System.ObjectDisposedException: Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it (or one of its parent scopes) has already been disposed.
This is confusing because:
The request pipeline hasn't finished yet (so the request scope should still be alive)
The executors themselves are registered as
SingleInstance
What I tried
- Checked the Web API request scope lifetime – it's still active when this happens. As I can see logs even after this exception.
Question
- Why does this happen even though the request is still running?