I am reworking an existing codebase to make better use of the autofac container. The situation I'm having is that a lot of things used to resolve their components straight from the container in a classic ServiceLocator
anti-pattern. I'm in the process of introducing proper unit-of-work schemes using LifetimeScope
.
The issue I'm facing is that some component must be resolved from a child LifetimeScope
as they are implementing IDisposable
and must be disposed. If they're resolved in the root scope that will never happen.
Is there any way to prevent some components from being resolved in the root scope? Crashing runtime is OK for this, since I'm going through these cases one by one and introducing scopes as needed. The only way I can think of to do this is to create a little dummy component that gets resolved once for the root lifetime scope and resolving in .InstancePerLifetimeScope()
, storing that statically somewhere. Then when a later component is resolved I'll get one of those dummy components and see if it's the same instance as the one that lifes in the root scope. It's a bit clunky though, and is there a better way?
You could try using 'per matching lifetime scope' registration:
containerBuilder.RegisterType<Foo>()
.As<IFoo>()
.InstancePerMatchingLifetimeScope("scope");
This way IFoo
can only be resolved when at least one ancestor lifetime scope is a tagged lifetime scope and its tag equals "scope"
. The root lifetime scope is usually not tagged, so when you try to resolve IFoo
from it, Autofac will throw an exception.
See the Autofac wiki for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With