使用Autofac传递NLog的声明类的类型 [英] Passing in the type of the declaring class for NLog using Autofac

查看:442
本文介绍了使用Autofac传递NLog的声明类的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

接着从这个问题开始,我想用autofac注入类型将声明对象放入NLog服务的构造函数中,以便它可以正确记录正在记录条目的类型.

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.

我的NLogService类看起来像这样...

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

但是它在应用程序启动时失败,因为它显然无法计算出要注入NLogService的构造函数的内容,并出现以下错误...

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...

没有发现以下构造函数 类型上的公共绑定标志" 'MyProduct.Domain.Services.Logging.NLogService' 可以用可用的调用 服务和参数:不能 解析参数'System.Type t' 构造函数'Void .ctor(System.Type)'.

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)'.

所以,我的问题是-我如何指示autofac注入调用类的类型?

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

我尝试过了...

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

但是我最后只得到了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.

推荐答案

可以使您的NLogService通用,即NLogService<T>并使用Autofac的

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

这篇关于使用Autofac传递NLog的声明类的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆