我为每个匹配的生命周期范围创建了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());
}
答案 0 :(得分:0)
您收到此错误,是因为您多次分配了AsyncLocal<T>
而不是一次。您应该实例化一次,然后多次分配Value
属性,该属性在每个线程中都是 unique 。
ie:
private static AsyncLocal<ILifetimeScope> _upperScope = new AsyncLocal<ILifetimeScope>();
然后
_upperScope.Value = container.BeginLifetimeScope("test");