Structuremap with MediatR

228 views
Skip to first unread message

Luke Bailey

unread,
Sep 14, 2017, 11:40:44 AM9/14/17
to structuremap-users

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>();


Jeremy Miller

unread,
Sep 14, 2017, 11:45:21 AM9/14/17
to structure...@googlegroups.com
This is really more of a MediatR question. From the SM side of things, if MediatR is using a nested container per request, I’d expect the unit of work to be scoped to the request. In your case, if the separate events are all separate logical transactions, I think you’ll
Need to explicitly control that yourself rather than using the default behavior here.

- Jeremy



--
You received this message because you are subscribed to the Google Groups "structuremap-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to structuremap-us...@googlegroups.com.
To post to this group, send email to structure...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/structuremap-users/f622eae4-a0df-4b1b-b969-9cb3c7f56818%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages