Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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;
- }
- }
Add Comment
Please, Sign In to add comment