Moving to AutofacServiceProviderFactory

Greetings.

I’m currently working on upgrading an old legacy system where they were previously using NServiceBus 2.x. We are upgrading to 7.x and are using Autofac as our IOC container. I noticed that previously they set up this container using a containerbuilder to register services and such like so:

var containerBuilder = new ContainerBuilder();
containerBuilder.Register(x => log).As();
//registering more sources/types here
IContainer container = containerBuilder.Build();

We’ve realized that this way:

endpointConfiguration.UseContainer<AutofacBuilder(x => x.ExistingLifetimeScope(scope));

Would now be an obsolete way of defining the custom builder for use.

I see now that the recommended way would be to use:

endpointConfiguration.UseContainer(new AutofacServiceProviderFactory(containerBuilder =>
{
containerBuilder.RegisterInstance(new MyService());
}));

However, my question is, is it possible to get a container reference using this new AutofacServiceProviderFactory? Before hand since we called containerBuilder.Build(), we had a reference to the container and thus, the scope. I was wondering if there was a way of still retrieving the scope/container that was built using the new method. If not, and we need it, is there another way to register the container for use, without using the obsolete AutofacBuilder.

Thanks,
Brenton

Hi Brenton_Pugh,

this is more of an Autofac question but I think you can get a reference to the container by doing:

ILifetimeScope container = null;

endpointConfiguration.UseContainer(new AutofacServiceProviderFactory(containerBuilder =>
{
    containerBuilder.RegisterInstance(new MyService());
    containerBuilder.RegisterBuildCallback(c => container = c);
}));

That said the reference will be assigned only after the container is built.

Cheers,
Tomek

1 Like

Ah, I see!

Apologies for having the wrong category, but I appreciate the response! This works perfectly and is just what I was looking for! :pray:t2:

Thanks,
Brenton

1 Like