问题描述
接着从这个问题开始,我想用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...
所以,我的问题是-我如何指示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的声明类的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!