The trick here is to let the UnitOfWork
live for the duration of a certain 'scope' and a single thread needs to be wrapped with such scope.
Registering instances in an explicit scope is done in Unity using the HierarchicalLifetimeManager
and starting a new child container:
container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
Wrapping a new child container scope around the execution of a task, can be done with a decorator:
public class HierarchicalLifetimeTaskDecorator : ITask
{
private readonly Container container;
public HierarchicalLifetimeTaskDecorator(Container container) {
this.container = container;
}
public void Execute() {
using (var scope = container.CreateChildContainer()) {
ITask realTask = scope.Resolve<ITask>();
realTask.Execute();
}
}
}