public class UnitOfWorkTracker
{
public UnitOfWork CurrentUnitOfWork { get; set; }
}
builder.Register<UnitOfWorkTracker>().ContainerScoped();
builder.Register(c => {
var result = new UnitOfWork();
c.Resolve<UnitOfWorkTracker>().CurrentUnitOfWork = result;
return result;
}).ContainerScoped();
builder.Register(c => new SomeRepository() { UoW = c.Resolve<UnitOfWorkTracker>().CurrentUnitOfWork) })
.ContainerScoped();
:) ? Just the first thing that came to mind. May not be the nicest if you want to autowire your repositories. There might be other variations on the UnitOfWorkTracker theme.
A better approach might be:
builder.Register(c => someCondition ? new UnitOfWork() : new NullUnitOfWork())
.As<IUnitOfWork>()
.ContainerScoped();
... That one depends on what that condition is.
Tyler was onto something too:
builder.Register(c => c.Resolve<UnitOfWorkTracker>().CurrentUnitOfWork).ContainerScoped();
That way you could put an instance in the UnitOfWorkTracker.CurrentUnitOfWork property when a 'real' UoW is going on (the value could be still be resolved from the container, perhaps by name.)
I think the second approach is the cleanest because within a nested container there will either be a UnitOfWork proper, or a NullUnitOfWork, never both. If this is not possible in your design, look closely at how the inner container corresponds with a unit of work - it
probably should be 1-1.
I'd guess there are many other approaches - some of them a bit crazier than others.
Hope this helps
NB