Search code examples
c#containersinversion-of-controlautofacnservicebus

NServiceBus Autofac child scope


I'm using NServiceBus 6 with NServiceBus.Autofac package.

I have some common interface ILogger which is registered in a custom Autofac Module (via overriding AttachToComponentRegistration method)

When I'm configuring NServiceBus with child Autofac container, unfortunately, all my message handlers could not resolve ILogger dependency.

        endpointConfiguration.UseContainer<AutofacBuilder>(
        customizations: customizations =>
        {
            var childContainer = _container.BeginLifetimeScope();
            customizations.ExistingLifetimeScope(childContainer);
        });

However, everything works perfect when NServceBus is configured in the following way (without child scopes = only root container):

        endpointConfiguration.UseContainer<AutofacBuilder>(
        customizations: customizations =>
        {
            customizations.ExistingLifetimeScope(_container);
        });

Does NServiceBus supports child Autofac scopes properly?


Solution

  • This is related to how Autofac deals with modules in child lifetime scopes. It appears that modules within child scopes are not handled as expected. Github issue here.

    A quick fix is to re-register the module whenever you create a new lifetime scope:

    endpointConfiguration.UseContainer<AutofacBuilder>(
    customizations: customizations =>
    {
        var childScope = _container.BeginLifetimeScope(b => b.RegisterModule<NLogModule>());
    
        customizations.ExistingLifetimeScope(childScope); // THIS LINE DOESN'T WORK PROPERLY
        //customizations.ExistingLifetimeScope(_container); // THIS LINE WORKS
    });