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

查看:58
本文介绍了使用 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 并使用 Autofac 的 开放泛型支持?

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

然后你可以这样做:

public class NLogService<T> : ILogger<T>
{
    private readonly Logger _logger;
    public NLogService()
    {
        _logger = LogManager.GetLogger(typeof(T).FullName);
    }
}

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

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