When someone calls the URL "/index/5", I want to return a view, and in parallel I want to start a new thread in which I want to figure out with some DB calls and business logic whether I should send someone else a notification. Here is a simplified representation of my setup, which gives an error.
How can I get my child scope to work in a parallel thread?
App Startup
var builder = new ContainerBuilder();
builder.RegisterType<MyRepository>().As<IMyRepository();
builder.RegisterType<Entities>().As<Entities>().InstancePerRequest();
var container = builder.Build();
Controller
private readonly IMyRepository _myRepository ;
public MyController(
IMyRepository myRepository
)
{
_myRepository = myRepository;
}
public async Task<ActionResult> Index(int id)
{
_myRepository.DoSomething(id);
return View();
}
Repository:
private ILifetimeScope _lifeTimeScopeChild = null;
public void DoSomething(int id){
//start new thread with child scope
using(var threadLifeTime = AutofacDependencyResolver.Current.ApplicationContainer.BeginLifetimeScope())
{
_lifeTimeScopeChild = threadLifeTime;
Thread t = new Thread(new ParameterizedThreadStart(MySeparateThread));
t.Start(id);
}
}
private void MySeparateThread(object id) {
var _entities = _lifeTimeScopeChild.Resolve<Entities>(); //IT CRASHES HERE
}
Error:
Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.
What I'm trying to accomplish: https://autofaccn.readthedocs.io/en/latest/lifetime/instance-scope.html#thread-scope