Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing in the type of the declaring class for NLog using Autofac

Following on from this question I would like autofac to inject the type of the declaring object into the constructor of my NLog service, so that it can correctly log which type is logging entries.

My NLogService class looks like this...

public class NLogService : ILogService
{
    private readonly Logger _logger;

    public NLogService(Type t)
    {
        var consumerType = t.DeclaringType.FullName;
        _logger = LogManager.GetLogger(consumerType);
    }

However it fails on app startup because it obviously cannot work out what to inject into the constructor of the NLogService with the following error...

None of the constructors found with 'Public binding flags' on type 'MyProduct.Domain.Services.Logging.NLogService' can be invoked with the available services and parameters: Cannot resolve parameter 'System.Type t' of constructor 'Void .ctor(System.Type)'.

So, my question is - how do i instruct autofac to inject the type of the calling class?

I tried this...

public NLogService(Type t)
    {
        var method = MethodBase.GetCurrentMethod();
        Type consumingType = method.DeclaringType;
        var consumerType = consumingType.FullName;
        var consumerType = t.DeclaringType.FullName;
        _logger = LogManager.GetLogger(consumerType);
    }

But i just end up with MyProduct.Domain.Services.Logging.NLogService

What i want is the type of the class that is doing the actual logging.

i have already tried this suggestion and it didnt work for me either.

like image 223
Baldy Avatar asked Dec 06 '22 20:12

Baldy


1 Answers

Could make your NLogService generic, i.e. NLogService<T> and use Autofac's open generics support?

Then you could do this:

public class NLogService<T> : ILogger<T>
{
    private readonly Logger _logger;
    public NLogService()
    {
        _logger = LogManager.GetLogger(typeof(T).FullName);
    }
}
like image 185
bentayloruk Avatar answered May 16 '23 06:05

bentayloruk