我使用NLOG该模块:
public class LoggingModule : Autofac.Module
{
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
{
registration.Preparing += OnComponentPreparing;
registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance);
}
private static void OnComponentPreparing(object sender, PreparingEventArgs e)
{
var t = e.Component.Activator.LimitType;
e.Parameters = e.Parameters.Union(
new[]
{
new ResolvedParameter((p, i) => IsLogger(p), (p, i) => GetLogger(t.FullName))
});
}
private static void InjectLoggerProperties(object instance)
{
var instanceType = instance.GetType();
var properties = instanceType
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => IsLogger(p) && p.CanWrite && p.GetIndexParameters().Length == 0);
foreach (var propToSet in properties)
{
propToSet.SetValue(instance, GetLogger(instanceType.FullName), null);
}
}
private static ILogger GetLogger(string name)
{
return LogManager.GetLogger(name);
}
private static bool IsLogger(ParameterInfo p)
{
return p.ParameterType == typeof (ILogger);
}
private static bool IsLogger(PropertyInfo p)
{
return p.PropertyType == typeof(ILogger);
}
}
一切似乎都做工精细,除了记录器的名称是空的/错的。 上的第一行OnComponentPreparing
,所述LimitType
是一个Meta<Lazy<IAutofacActionFilter>>[]
而不是预期的LogControllerActionFilterAttribute
。 如何获取记录程序的正确类型的名字吗? 在我的日志,这是作为记录器名称:
0文化=中性公钥= b77a5c561934e089]] []
编辑:
这是一个简短而完整的程序演示了这个问题。 你需要以上以及模块实现。
internal class Program
{
private static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterModule<LoggingModule>();
builder.RegisterType<Foo>().As<IFoo>();
var container = builder.Build();
// This prints out "0, Culture=neutral, PublicKeyToken=b77a5c561934e089]][]" for the logger name
foreach (var metalazyfoo in container.Resolve<Meta<Lazy<IFoo>>[]>())
metalazyfoo.Value.Value.Work(5);
// This prints out "Foo" for the logger name
container.Resolve<Meta<Lazy<IFoo>>>().Value.Value.Work(6);
Console.WriteLine("=== Done ===");
Console.ReadLine();
}
}
public class Foo : IFoo
{
private readonly Logger _logger;
public Foo(Logger logger)
{
_logger = logger;
}
public void Work(int x)
{
_logger.Debug(x);
}
}
public interface IFoo
{
void Work(int x);
}