5

使用 Autofac,我可以注册一个类以使用属性注入来解析接口,使用以下代码:

builder.RegisterType<Log4NetAdapter>()
       .As<ILogger>()
       .PropertiesAutowired()
       .InstancePerDependency();

但是,我的Log4NetAdapter类有一个构造函数参数,它需要调用类的名称。这样,我可以根据调用类的名称记录事件。

public class Log4NetAdapter : ILogger
{
    private readonly ILog _logger;

    public Log4NetAdapter(string logName)
    {
        _logger = LogManager.GetLogger(logName);
    }

    ...
}

typeof(dependency).Name鉴于每个依赖项都有自己的Log4NetAdapter实例,我如何将依赖项的名称(即)注入到属性注入类的构造函数中?

4

2 回答 2

4

更新:LogInjectionModule示例以及Autofac 如何进行属性注入的基础上,我扩展了模块以进行构造函数和属性注入。

注意:我已经修复了传入的类型LogManagerOnComponentPreparing使用声明类型。这使得例如Resolve<Func<Service>>使用正确的日志类型。

    using System.Linq;
    using log4net;

    public class LogInjectionModule : Module
    {
        protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
        {
            registration.Preparing += OnComponentPreparing;
            registration.Activating += OnComponentActivating;
        }

        private static void OnComponentActivating(object sender, ActivatingEventArgs<object> e)
        {
            InjectLogProperties(e.Context, e.Instance, false);
        }

        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))
                });
        }

        private static void InjectLogProperties(IComponentContext context, object instance, bool overrideSetValues)
        {
            if (context == null) throw new ArgumentNullException("context");
            if (instance == null) throw new ArgumentNullException("instance");

            var instanceType = instance.GetType();
            var properties = instanceType
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(pi => pi.CanWrite && pi.PropertyType == typeof(ILog));

            foreach (var property in properties)
            {
                if (property.GetIndexParameters().Length != 0)
                    continue;

                var accessors = property.GetAccessors(false);
                if (accessors.Length == 1 && accessors[0].ReturnType != typeof(void))
                    continue;

                if (!overrideSetValues &&
                    accessors.Length == 2 &&
                    (property.GetValue(instance, null) != null))
                    continue;

                ILog propertyValue = LogManager.GetLogger(instanceType);
                property.SetValue(instance, propertyValue, null);
            }
        }
    }

关于如何使用该模块,这里有一个示例:

public class Service
{
    public Service(ILog log) { ... }
}

var cb = new ContainerBuilder();
cb.RegisterModule<LogInjectionModule>();
cb.RegisterType<Service>();
var c = cb.Build();

var service = c.Resolve<Service>();
于 2013-01-23T16:52:11.643 回答
1

您仅用于logName通过名称有效解析 an ILog,那么为什么不直接注入 anILog呢?

public class Log4NetAdapter : ILogger
{
    private readonly ILog _logger;

    public Log4NetAdapter(ILog logger)
    {
        _logger = logger;
    }

    ...
}

好的,所以现在我只是稍微移动了这个问题,但我也减少了它与其他类的耦合,即LogManager.

所以如果我使用统一,我会这样做以确保我得到正确的记录器:

var childContainer = container.CreateChildContainer();
childContainer.RegisterInstance<ILog>(LogManager.GetLogger(logName));
var adaptor = childContainer.Resolve<Log4NetAdapter>();

子容器阻止任何其他代码访问它ILog。您可以随心所欲地执行此操作,我对您的代码一无所知。

于 2013-01-23T16:46:27.007 回答