Guest User

Untitled

a guest
Mar 23rd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. /*
  2. An Autofac lifetime that ensures dependencies are only resolved from scoped containers.
  3. This acts like a safety-net to prevent captive dependencies:
  4.  
  5. ```
  6. // Register some short-lived dependency using the `NonRootScopeLifetime`
  7. var registration = builder.Register(c => c.Resolve<IStore>().BeginSession()).As<ISession>();
  8.  
  9. registration.RegistrationData.Lifetime = new NonRootScopeLifetime();
  10. ```
  11. */
  12.  
  13. class NonRootScopeLifetime : IComponentLifetime
  14. {
  15. public ISharingLifetimeScope FindScope(ISharingLifetimeScope mostNestedVisibleScope)
  16. {
  17. if (mostNestedVisibleScope.ParentLifetimeScope == null) throw new InvalidOperationException("Trying to resolve scoped service from root container.");
  18. if (mostNestedVisibleScope.ParentLifetimeScope.ParentLifetimeScope != null) throw new InvalidOperationException("This might be ambiguous.");
  19. return mostNestedVisibleScope;
  20. }
  21. }
Add Comment
Please, Sign In to add comment