Structuremap with MediatR

Skip to first unread message

Luke Bailey

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 ( 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 =>

For<SingleInstanceFactory>().Use<SingleInstanceFactory>(ctx => t => ctx.GetInstance(t));
For<MultiInstanceFactory>().Use<MultiInstanceFactory>(ctx => t => ctx.GetAllInstances(t));


Jeremy Miller

Sep 14, 2017, 11:45:21 AM9/14/17
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
To post to this group, send email to
To view this discussion on the web visit
For more options, visit

Reply all
Reply to author
0 new messages