1

我在这个模块中使用 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);
    }
}

一切似乎都很好,除了记录器的名称是空的/错误的。在 的第一行OnComponentPreparingLimitType是 aMeta<Lazy<IAutofacActionFilter>>[]而不是预期的LogControllerActionFilterAttribute。如何获得记录器的正确类型名称?在我的日志中,这是作为记录器名称给出的:

0,文化=中性,PublicKeyToken=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);
}
4

1 回答 1

1

这里的 LimitType 应该是

var t = e.Component.Target.Activator.LimitType;

代替

var t = e.Component.Activator.LimitType;

这是为了避免使用激活器的类型创建记录器,而不是被激活的底层组件的类型。这就是为什么你得到 Meta>[] 而不是 LogControllerActionFilterAttribute。

于 2015-05-06T20:20:53.247 回答