Check if component is enabled in external LifetimeScope

I am reworking the existing code base to make better use of the autofac container. The situation that I am facing is that many things are used to solve their components directly from the container in the classic anti- ServiceLocator template. I am in the process of implementing the right workflows using LifetimeScope .

The problem I am facing is that some component must be allowed from the child LifetimeScope , as they implement IDisposable and must be removed. If they are allowed in the root area that will never happen.

Is there a way to prevent the removal of some components in the root area? A run-time failure is normal, as I look through these cases one by one and represent the areas if necessary. The only way I can do this is to create a small dummy component that will be resolved once for the root lifecycle area and resolved in .InstancePerLifetimeScope() , storing it statically somewhere. Then, when a later component is resolved, I will get one of these dummy components and see if it is the same instance as the one that lives in the root area. This is a little awkward, and is there a better way?

+6
source share
1 answer

You can try to use the registration "for each validity period":

 containerBuilder.RegisterType<Foo>() .As<IFoo>() .InstancePerMatchingLifetimeScope("scope"); 

This IFoo method can only be allowed when at least one area of ​​the ancestor’s life is a scope with tags and its tag is "scope" . The root lifecycle area is usually not marked, so when trying to allow IFoo from it, Autofac throws an exception.

See the Autofac wiki for more information.

+1
source

Source: https://habr.com/ru/post/944535/


All Articles