I want to use dryioc to manage dependencies required by multiple threads. I want to start threads passing each a job which requires dependencies to be resolved by ioc. Not sure what this should look like ideally any assistance appreciated.
1 回答
If you need service scoped to a thread (a single instance per thread), then set ThreadScopeContext
for container:
RootContainer = new Container(scopeContext: new ThreadScopeContext());
RootContainer.Register<IService, MyService>(Reuse.InCurrentScope);
// in your thread
using (RootContainer.OpenScope())
{
var service = RootContainer.Resolve<IService>();
// use the service
}
If you need service to start live in new thread, but then propagate the same instance through async/await
calls (possibly on different threads), use AsyncExecutionFlowScopeContext
.
Scope context in DryIoc is third party object, independent from container, where you may store open scopes, e.g. in thread static, or AsyncLocal
variable.
Another way (the default behavior) is to associate open scope with new scoped container, but then you need the reference to this new container in order to resolve. Here I am not using any scope context, but need to resolve from scopedContainer
instead of root one:
RootContainer = new Container(); // without ambient scope context
RootContainer.Register<IService, MyService>(Reuse.InCurrentScope);
// in your thread
using (var scopedContainer = RootContainer.OpenScope())
{
var service = scopedContainer.Resolve<IService>();
// use the service
}