Autofac System.ArgumentNullException:值不能为null。参数名称:上下文

时间:2018-07-05 11:23:06

标签: c# multithreading autofac

我为每个匹配的生命周期范围创建了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());
}

Click here for stack trace

1 个答案:

答案 0 :(得分:0)

您收到此错误,是因为您多次分配了AsyncLocal<T>而不是一次。您应该实例化一次,然后多次分配Value属性,该属性在每个线程中都是 unique

ie:

private static AsyncLocal<ILifetimeScope> _upperScope = new AsyncLocal<ILifetimeScope>();

然后

_upperScope.Value = container.BeginLifetimeScope("test");