我有一个记录器如下:
public class Logger : ILogger
{
private ILogger _logger;
public Logger(Type type)
{
_logger = LogManager.CreateLogger(type);
}
.... removed
我正在尝试构建一个日志模块:
public class LogModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
const string propertyNameKey = "Autofac.AutowiringPropertyInjector.InstanceType";
builder.RegisterType<Logger>().As<ILogger>();
base.Load(builder);
}
}
我必须找到并将类型注入Logger
,类似this问题,但是that question执行属性注入,我需要注入ctor。
如何获取上下文日志记录,即每个类型的日志?
答案 0 :(得分:-1)
您可以使用注册对象的Preparing
。此代码取自autofac page。
public class LoggingModule : Autofac.Module
{
private static void InjectLoggerProperties(object instance)
{
var instanceType = instance.GetType();
// Get all the injectable properties to set.
// If you wanted to ensure the properties were only UNSET properties,
// here's where you'd do it.
var properties = instanceType
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.PropertyType == typeof(ILog) && p.CanWrite && p.GetIndexParameters().Length == 0);
// Set the properties located.
foreach (var propToSet in properties)
{
propToSet.SetValue(instance, LogManager.GetLogger(instanceType), null);
}
}
private static void OnComponentPreparing(object sender, PreparingEventArgs e)
{
e.Parameters = e.Parameters.Union(
new[]
{
new ResolvedParameter(
(p, i) => p.ParameterType == typeof(ILog),
(p, i) => LogManager.GetLogger(p.Member.DeclaringType)
),
});
}
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
{
// Handle constructor parameters.
registration.Preparing += OnComponentPreparing;
// Handle properties.
registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance);
}
}
此代码:
private static void OnComponentPreparing(object sender, PreparingEventArgs e)
{
e.Parameters = e.Parameters.Union(
new[]
{
new ResolvedParameter(
(p, i) => p.ParameterType == typeof(ILog),
(p, i) => LogManager.GetLogger(p.Member.DeclaringType)
),
});
}
将新记录器(使用类名称)注入CTOR。
class ClassA
{
...
ClassA(ILog logger) => this.logger = logger; // logger was created by Autofac via LogManager.GetLogger("ClassA")
}
希望这是你要找的东西。