nblumhardt / autofac-serilog-integration

Contextual logger injection for Autofac using Serilog
Apache License 2.0
70 stars 25 forks source link

ContextualLoggingModule gets registered twice when using Autofac's assembly scanning #9

Closed augustoproiete closed 8 years ago

augustoproiete commented 8 years ago

Related to Autofac issues:

I have a scenario where I have a specific ILogger instance to be registered with Autofac via the RegisterLogger extension method`:

var builder = new ContainerBuilder();
builder.RegisterLogger(_mySpecificILoggerInstance);

However, later in the code, there's a call to RegisterAssemblyModules which will pickup the AutofacSerilogIntegration assembly and will register the ContextualLoggingModule again, but now with a null instance of ILogger and will cause it to use the static instance Log.Logger - which is not the instance desired.

e.g.

var assembliesInAppDomain = AppDomain.CurrentDomain.GetAssemblies().ToArray();
builder.RegisterAssemblyModules(assembliesInAppDomain);

I think the ideal scenario would be to have a way to tell Autofac to skip registering the ContextualLoggingModule given we want it to be registered only via the RegisterLogger extension method.

A quick attempt to make ContextualLoggingModule internal, produce the same results (Autofac registers it anyway, by design I think).

A second quick attempt to make ContextualLoggingModule constructor's also internal, causes an exception during registration as Autofac can still see the module but can't find a suitable constructor, and bombs.

nblumhardt commented 8 years ago

Hi Caio!

I think the issue is really this line:

var assembliesInAppDomain = AppDomain.CurrentDomain.GetAssemblies().ToArray();

To get a sane result from this code you pretty much have to choose the assemblies based on some predicate, e.g. where the name starts with "MyCompany..." or similar. Pushing some kind of scheme down into Autofac to try to pick the right ones seems dubious, as anyone who later comes to read this code will have to look up what the scheme is anyway.

My $0.02 :-)

Any reason not to apply some kind of filter to the assembly names?

Cheers!

augustoproiete commented 8 years ago

Hey Nick,

Yeah... The example above was simplified for illustration purposes. My scenario is a bit more complex, and I have filters to get a small set of assemblies to be scanned... Let's say I have something like:

var assembliesInAppDomain = AppDomain.CurrentDomain.GetAssemblies()
    .Where(asm => asm.FullName.StartsWith("MyCompanyName."))
    .ToArray();

Problem is that inside one of the "MyCompanyName." assemblies there's your ContextualLoggingModule (as source code, not binary, because of reasons), and that causes the issue.

Regardless of my wacky scenario, I opened the issue because I think you would expect the module to only be registered via the RegisterLogger extension method, and not by Autofac assembly scanning, isn't it?