I am using Simple Injector to manage the lifetime of my injected dependencies (in this case UnitOfWork), and I am very happy as having a separate decorator rather than my service or command handler looking after saving and disposing makes code a lot easier when writing business logic layers (I follow the architecture that is outlined in this blog post).
The above is working perfectly (and very easily) by using the Simple Injector MVC NuGet package and the following code during the construction of the composition root container, if more than one dependency exists in the graph the same instance is injected across all - perfect for Entity Framework model context.
private static void InitializeContainer(Container container)
{
container.RegisterPerWebRequest<IUnitOfWork, UnitOfWork>();
// register all other interfaces with:
// container.Register<Interface, Implementation>();
}
I now need to run some background threads and understand from Simple Injector documentation on threads that commands can be proxied as follows:
public sealed class TransactionCommandHandlerDecorator<TCommand>
: ICommandHandler<TCommand>
{
private readonly ICommandHandler<TCommand> handlerToCall;
private readonly IUnitOfWork unitOfWork;
public TransactionCommandHandlerDecorator(
IUnitOfWork unitOfWork,
ICommandHandler<TCommand> decorated)
{
this.handlerToCall = decorated;
this.unitOfWork = unitOfWork;
}
public void Handle(TCommand command)
{
this.handlerToCall.Handle(command);
un