My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
ThreadScoping  
Nested containers provide stronger thread binding
Autofac2
Updated Aug 6, 2010 by nicholas...@gmail.com

Introduction

Autofac 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().

Comment by yves.rey...@gmail.com, Apr 20, 2010

1. CreateInnerContainer?() is Autofac 1.4.x wording 2. Is this guidance still valid for 2.x?

Comment by project member nicholas...@gmail.com, Apr 20, 2010

Yves - yes, this is still valid for 2.x, and yes, the BeginLifetimeScope() and CreateInnerContainer() methods are equivalent in this scenario.

Comment by kot.bege...@gmail.com, Nov 9, 2011

And how do we get "container" variable in ThreadStart? method?


Sign in to add a comment
Powered by Google Project Hosting