bugthesystem / Autofac.Extras.NLog

An Autofac module to integrate Autofac and NLog, it supports both constructor and property injection.
MIT License
50 stars 18 forks source link

overwrites my registration #24

Open mduman opened 1 year ago

mduman commented 1 year ago

Hello,

In some cases I want to register my own logger (with a specific logger name) for a specific generic class (my generic class has a very ugly full name to see on log files) but this module overwrites my registration.

1- How can i use specific logger names for specific classes (still accepting ILogger as a parameter on class constructor). 2- Can checking already existing registration on "NLogMiddleware" class help?

CNBoland commented 1 year ago

Can you create an application that demonstrates the overwrite?

JPasterkampRotec commented 11 months ago

I have the same issue and created a (.NET 8) console app to reproduce the issue. The console app uses Autofac 6.5.0, NLog 5.2.7 and Autofac.Extras.NLog 4.0.1.

Is there any way how I can manipulate the logger naming behavior for a single registration?

using Autofac;
using Autofac.Core;
using Autofac.Extras.NLog;
using NLog;

var builder = new ContainerBuilder();
builder.RegisterModule<NLogModule>();
builder.RegisterType<Wrong>()
    .WithParameter(new ResolvedParameter(
        (param, context) => param.ParameterType == typeof(ILogger),
        (param, context) => LogManager.GetLogger("Correct")))
    .SingleInstance();
IContainer container = builder.Build();

// This instance will now have a logger with name "Wrong" instead of the expected "Correct"
Wrong instance = container.Resolve<Wrong>();
Console.WriteLine(instance.Logger.Name);
Console.ReadKey();

public class Wrong
{
    public ILogger Logger { get; }

    public Wrong(ILogger logger)
    {
        Logger = logger;
    }
}