Created
March 15, 2018 03:52
-
-
Save KodrAus/5dd3e84a3d182ee1437950fb0f75223d to your computer and use it in GitHub Desktop.
NonRootScopeLifetime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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