masstransitstructuremap3

Masstransit Structuremap per message scope


I am using a repository pattern with Entity Framework where i inject the DbContext in each repository. I have multiple repositories for a single MassTransit consumer. Each repository must share the DbContext in the scope of consuming a single message.

I need to put a per-message lifecycle scope on the DbContext. How can i do that?

        For<DbContext>().Use<DbContext>();
        For<MyConsumer>().Use<MyConsumer>();
        For<IRepository1>.Use<Repository1>();
        For<IRepository2>.Use<Repository2>();
        For<IServiceBus>().Singleton().Use("bookingServicesServiceBus", ctx =>
        {
            var bus = ServiceBusFactory.New(sbc =>
            {
                sbc.Subscribe(s => s.LoadFrom(ctx.GetInstance<IContainer>()));
            });

            return bus;
        });

Solution

  • Doh the solution was obvious. The MassTransit.Structuremap nuget package actually takes care of the per-message scope using nested containers.

    However I had the DbContext registred as HybridHttpOrThreadLocalScoped for some unkown reason.