1

I have a class something like this:

public class ABCHelper : ABCBase, IABCHelper
{
    public ABCHelper()
        : base(LogManager.GetCurrentClassLogger())
    {
    }
}


public class ABCBase : IABCBase
{
        protected readonly Logger logger;

        protected ABCBase(Logger logger)
        {
            this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }
        public async Task<HttpResponseMessage> MakeAsyncCall(HttpRequestMessage request)
        {
            // some code
            this.logger.Info("some string");
        }
}   

Class registration in Unity:

container.RegisterType<IABCHelper, ABCHelper>();

When I call MakeAsyncCall in some code flow, NLog logs the classname as "DynamicBuildPlanGenerationContext".

I was expecting "ABCHelper" instead of "DynamicBuildPlanGenerationContext".

What am I missing?

Julian
  • 33,915
  • 22
  • 119
  • 174
starkk92
  • 5,754
  • 9
  • 43
  • 59

1 Answers1

0

First of all, it a bit debatable if ABCHelper is your current class, as it isn't constructed yet ;)

I think Unity is using some tricks for efficiently constructing the dependencies. The description of DynamicBuildPlanGenerationContext

This object tracks the current state of the build plan generation, accumulates the Microsoft intermediate language, provides the preamble & postamble for the dynamic method, and tracks things like local variables in the generated MSIL so that they can be reused across MSIL generation strategies.

NLog tries to find the current class name by checking the callstack, but can't find it probably due to optimizations.

I think case the easiest fix is by using named loggers, e.g. by using LogManager.GetLogger(string)

public class ABCHelper : ABCBase, IABCHelper
{
    public ABCHelper()
        : base(LogManager.GetLogger(nameof(ABCHelper)))
    {
    }
}

Side note, maybe it's because of the demo, but I don't see here the logger proper injected. If you don't want to use DI for loggers, you could just create a static field?

If you do like to use injected loggers, then I would recommend to checkout Microsoft.Extensions.Logging with NLog.Extensions.Logging which also works with Unity and .NET Framework. This could be also useful then: Resolve generic Microsoft.Extensions.Logging.ILogger<T> with Unity - get InvalidCastException

Or you could use

Julian
  • 33,915
  • 22
  • 119
  • 174