Message Handler resolves different DbContext than Unit of Work

Greetings,

I am currently upgrading NServiceBus from 2.x to 7.x. This has been quite the task, and I’m having a problem with my message handlers resolving the DbContext from my Autofac container. The DbContext in the message handler, is resolved through DI, and the actual save changes call is through a Unit of Work in a separate project. The unit of work is using the root scope while the Handler is using a different scope (where the data is manipulated).

In the past, we used Autofac2Builder to pass in a preconfigured container to be used by nServiceBus:

var config = NServiceBus.Configure.With();
            config.Autofac2Builder(Container)
                .XmlSerializer()
                .MsmqSubscriptionStorage()
                .MsmqTransport()
                    .IsTransactional(true)
                    .PurgeOnStartup(false)
                .UnicastBus()
                    .ImpersonateSender(true);

Then when a Message Handler used a Unit of Work (using statement) we would call a Container.Get() to resolve the DbContext which would first pull back the following scope.

// next look in NServiceBus context
if (Autofac2ObjectBuilder.MessageLifetimeScope != null)
    return Autofac2ObjectBuilder.MessageLifetimeScope;

This allowed the DbContext in the handler and the unit of work to be the same.

This utilized NServiceBus.ObjectBuildre.Autofac2 which no longer exists. And normally when the Unit of Work in the Message Handler tried to resolve the context it used this scope.

Is it still possible to resolve the DbContext in a Message Handler, through DI, and in a unit of work (using statement) resolve the same DbContext as done previously using the Autofac2Builder.

Thanks!
-Brenton

That code is from a very long time ago, it is still available at NServiceBus/src/impl/ObjectBuilder/ObjectBuilder.Autofac2 at 2.0 · Particular/NServiceBus · GitHub if you would be interested in researching specific behavior.

Yes, you can still register your DbContext and resolve that in multiple invoked handlers via DI and have a single call to SaveChanges.

The unit of work behavior that would invoke save changes is still possible. Guidance is available at Unit of Work • NServiceBus • Particular Docs

1 Like

Awesome! I have looked everywhere for some sort of clarification on what Autofac2 might be doing behind the scenes, but it being so long ago, I couldn’t find much! I may need to do some refactoring here then to get the current unit of work up to date with the new way of doing things, as per your Unit of Work link. This app I’m upgrading was written back in 2012 so it’s been…challenging lol.

Thanks for the guidance!
-Brenton