Autofac - resolving dependencies in multi thread environment
To give each thread its own lifetime scope, you just need to register your IsolatedLifetimeScopeFactory
as SingleInstance
. This will solve your concerns 2) and 3)
[TestMethod]public void MyTestMethod(){ var cb = new ContainerBuilder(); cb.RegisterGeneric(typeof(IsolatedLifetimeScopeFactory<>)) .SingleInstance(); var container = cb.Build(); using (var scope1 = container.BeginLifetimeScope("scope1")) using (var scope2 = scope1.BeginLifetimeScope("scope2")) { var factory = scope2.Resolve<IsolatedLifetimeScopeFactory<object>>(); var tag = factory._scope.Tag; // made _scope public for testing purposes Assert.AreNotEqual("scope1", tag); Assert.AreNotEqual("scope2", tag); // This particular string "root" is probably not guaranteed behavior, but // being in the root scope is guaranteed for SingleInstance registrations. Assert.AreEqual("root", tag); }}
Your concern 1) could be solved by using a different abstraction. For example, you could add this to the IsolatedLifetimeScopeFactory
public Autofac.Features.OwnedInstances.Owned<TA> Create(){ return _scope.Resolve<Autofac.Features.OwnedInstances.Owned<TA>>();}
And you could hide Owned
behind an abstraction if you really wanted to, although I would say that's overkill.