I have command Handlers (IRequestHandler) that require a Unit Of Work class to do their database access. I have a decorator for the handlers that commits the Unit of Work. I also have event handlers (INotificationHandler) that follow the same pattern. The decorator class also publishes any events that may have been created by the handler.
The main handler and the decorator need to have the same Unit of Work in order to function. The issue that I am having is that when the decorator publishes events, those event handles get the same Unit of Work that the original command handler had. Each event is a separate transaction and needs to have it's own Unit of Work.
My understanding of MediatR (
https://github.com/jbogard/MediatR) is when I send or publish, the current mediator class uses the current container and gets handlers according to the message. This is a webforms project, so the container is per http request. So what I need is a configuration that when I request a new instance of a handler, any dependencies it or it's decorator needs are the same objects. But if I request a new handler, those dependencies are different.
Here is my configuration.
Scan(x =>
{
x.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<>));
x.ConnectImplementationsToTypesClosing(typeof(INotificationHandler<>));
For<SingleInstanceFactory>().Use<SingleInstanceFactory>(ctx => t => ctx.GetInstance(t));
For<MultiInstanceFactory>().Use<MultiInstanceFactory>(ctx => t => ctx.GetAllInstances(t));
For<IMediator>().Use<Mediator>();
});
For(typeof(IRequestHandler<>)).DecorateAllWith(typeof(CommandHandlerUnitOfWorkDecorator<>));
For(typeof(INotificationHandler<>)).DecorateAllWith(typeof(EventHandlerUnitOfWorkDecorator<>));
For<IUnitOfWork>().Use<NHibernateUnitOfWork>();