Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
An Autofac lifetime that ensures dependencies are only resolved from scoped containers.
This acts like a safety-net to prevent captive dependencies:
// Register some short-lived dependency using the `NonRootScopeLifetime`
var registration = builder.Register(c => c.Resolve<IStore>().BeginSession()).As<ISession>();
registration.RegistrationData.Lifetime = new NonRootScopeLifetime();
class NonRootScopeLifetime : IComponentLifetime
public ISharingLifetimeScope FindScope(ISharingLifetimeScope mostNestedVisibleScope)
if (mostNestedVisibleScope.ParentLifetimeScope == null) throw new InvalidOperationException("Trying to resolve scoped service from root container.");
if (mostNestedVisibleScope.ParentLifetimeScope.ParentLifetimeScope != null) throw new InvalidOperationException("This might be ambiguous.");
return mostNestedVisibleScope;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.