Skip to content
This repository has been archived by the owner on Dec 12, 2022. It is now read-only.

Incorrect dependencies resolving inside child Autofac lifetime scope #48

Closed
alex-training opened this issue Sep 4, 2017 · 6 comments
Closed

Comments

@alex-training
Copy link

alex-training commented Sep 4, 2017

Hi guys!

I'm trying to host multiple NServiceBus endpoints in my custom self-written host, so I was thinking about creating a child Autofac lifetime scope per endpoint.

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

For some reason such approach doesn't work and I'm getting errors while resolving dependencies for my message handlers.

Probably I can use a root container everywhere instead, but I'm afraid about endpoints isolation.
Something like this:

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

What I'm doing wrong?
Could you guys please help with some advice?

I've created a sample to demonstrate the issue:
a sample

Many thanks

@WilliamBZA
Copy link
Member

Hey @alex-training

It seems to be related to how Modules are used within updated containers in child scopes. I'll let you know once i find something more concrete though

@WilliamBZA
Copy link
Member

Yep, it appears that modules within child scopes are not handled as expected within autofac. Github issue here.

I'm not sure we can do much ourselves here as this touches very deeply with autofac internals.

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

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
});

@alex-training
Copy link
Author

Hey @WilliamBZA
I've got it, thank you for your quick reply!

@WilliamBZA
Copy link
Member

Great, I'm going to close this in the meantime.

By the way, we have a sample showing NLog integration that doesn't require an Autofac module. It uses a community port for NLog that @SimonCropp created.

@WilliamBZA
Copy link
Member

Oops! It's not community port anymore, it's officially supported.

@alex-training
Copy link
Author

alex-training commented Sep 6, 2017

Hi @WilliamBZA,

That's a cool sample, indeed.
However, later I would like to share and inject an abstract ILogger interface via constructor injection.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants