c# - Autofac System.ArgumentNullException:值不能为空。参数名称:上下文
问题描述
我为每个匹配的生命周期范围创建了 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());
}
解决方案
您收到此错误是因为您分配了AsyncLocal<T>
不止一次而不是仅分配一次。您应该将其实例化一次,然后Value
多次分配该属性,该属性对于每个线程都是唯一的。
IE :
private static AsyncLocal<ILifetimeScope> _upperScope = new AsyncLocal<ILifetimeScope>();
进而
_upperScope.Value = container.BeginLifetimeScope("test");
推荐阅读
- java - 是否可以通过 Android Studio 创建 Excel 电子表格?
- angular - 只运行被点击的按钮
- java - 在真实物体上模拟“何时”
- excel - Redim Preserve 触发“超出范围”错误
- sql - 在 Microsoft SQL Server Management Studio 中获取此错误消息
- php - 警告:在...中遇到的非数字值如何解决?
- javascript - 如何使用 react-router 设置嵌套路由以使用 ReactJs 加载嵌套上下文?
- c++ - 为什么 setjmp/longjmp 的这种用法是未定义的行为?
- r - igraph 的情节:如何突出显示一组顶点
- python-3.x - 在 Python 中导入加密的 Cython 模块