I created autofac instance per matching lifetime scope and create child scope if parent scope already exist but i got exception.
Please see the code and stack trace below.
Code
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());
}
You get this error because you assigned the AsyncLocal<T>
more than once instead of only once. You should instantiate it once and then assign the Value
property multiple time, this property will be unique per thread.
ie :
private static AsyncLocal<ILifetimeScope> _upperScope = new AsyncLocal<ILifetimeScope>();
and then
_upperScope.Value = container.BeginLifetimeScope("test");
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments