Я создал экземпляр autofac для каждой соответствующей области действия и создал дочернюю область, если родительская область уже существует, но я получил исключение.
См. Код и трассировку стека ниже.
Код
public static class App {
private static AsyncLocal<ILifetimeScope> _upperScope;
public static AsyncLocal<int> Number = new AsyncLocal<int>();
public static ILifetimeScope NewScope(IContainer container) {
if (_upperScope?.Value != null)
return _upperScope.Value.BeginLifetimeScope();
_upperScope = new AsyncLocal<ILifetimeScope> {Value = container.BeginLifetimeScope("test")};
_upperScope.Value.CurrentScopeEnding += (sender, args) => _upperScope.Value = null;
return _upperScope.Value;
}
}
[Fact]
public void Test1() {
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<ClassOne>().AsSelf().InstancePerMatchingLifetimeScope("test");
var container = containerBuilder.Build();
var tasks = new List<Task>();
tasks.Add(Task.Run(() => {
using (var scope = App.NewScope(container)) {
scope.Resolve<ClassOne>();
}
}));
tasks.Add(Task.Run(() => {
using (var scope = App.NewScope(container)) {
scope.Resolve<ClassOne>();
}
}));
Task.WaitAll(tasks.ToArray());
}
Нажмите здесь для отслеживания стека