|
ThreadScoping
Nested containers provide stronger thread binding
Autofac2 IntroductionAutofac can enforce that objects bound to one thread will not satisfy the dependencies of a component bound to another thread. This is done using lifetime scope: var builder = new ContainerBuilder(); builder.RegisterType<MyThreadScopedComponent>() .InstancePerLifetimeScope(); var container = builder.Build(); Then, each thread gets its own inner context: void ThreadStart()
{
using (var threadLifetime = container.BeginLifetimeScope())
{
var thisThreadsInstance = threadLifetime.Resolve<MyThreadScopedComponent>();
}
}Each thread executing through ThreadStart() will then get its own instance of MyThreadScopedComponent - which is essentially a "singleton" in the lifetime scope. Because scoped instances are never provided to outer scopes, it is easier to keep thread components separated. If you would like to enforce this even more heavily, use tags to associate the thread-scoped components with the inner lifetime (they'll still have dependencies from the factory/singleton components in the outer container injected.) The result of this approach looks something like:
The 'contexts' in the diagram are the containers created with CreateInnerContainer(). | |
1. CreateInnerContainer?() is Autofac 1.4.x wording 2. Is this guidance still valid for 2.x?
Yves - yes, this is still valid for 2.x, and yes, the BeginLifetimeScope() and CreateInnerContainer() methods are equivalent in this scenario.
And how do we get "container" variable in ThreadStart? method?