Skip to content

Instantly share code, notes, and snippets.

@KodrAus
Created March 15, 2018 03:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KodrAus/5dd3e84a3d182ee1437950fb0f75223d to your computer and use it in GitHub Desktop.
Save KodrAus/5dd3e84a3d182ee1437950fb0f75223d to your computer and use it in GitHub Desktop.
NonRootScopeLifetime
/*
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