Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if component is resolved in outermost LifetimeScope

Tags:

c#

autofac

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?

like image 960
Dervall Avatar asked May 08 '13 14:05

Dervall


1 Answers

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.

like image 110
ErikHeemskerk Avatar answered Oct 05 '22 11:10

ErikHeemskerk