如何将AutoFac连接到Common.Logging?

Jer*_*acs 1 c# unit-testing dependency-injection mocking autofac

我有一个像这样的课程:

public class LoggedFoo
{
    private readonly ILog _logger;

    public LoggedFoo(ILog logger)
    {
        this._logger = logger;
    }

    public DoStuff()
    {
        this._logger.Info(i => i("Doing stuff..."));
    }
}
Run Code Online (Sandbox Code Playgroud)

业务需求之一是正在为某些功能生成日志,所以自然地我想模拟出ILog进行验证。

但是,Common.Logging库支持基于类型的记录器,大致如下:

var logger = LogManager.GetLogger<LoggedFoo>();
Run Code Online (Sandbox Code Playgroud)

...要么:

var logger = LogManager.GetLogger(typeof(LoggedFoo));
Run Code Online (Sandbox Code Playgroud)

问题是,我们正在使用AutoFac进行依赖项注入,而我无法弄清楚如何ILog根据要为注入实例化的类来实例化an 。

我该怎么写?我正在使用最新的Nuget版本的AutoFac。

Old*_*Fox 5

我可以考虑两种方法来实现它:(很抱歉,我的国家时间是凌晨1:50 ...)

  1. 更改ILog为ILog<T>,然后将其注册为Open Generic。

  2. 使用动态提供程序,它允许您使用上下文进行解析。

Autofac的网站上有一个示例,它似乎正是您所寻找的东西。

使用上下文解决依赖关系:

private static void OnComponentPreparing(object sender, PreparingEventArgs e)
{
    var t = e.Component.Target.Activator.LimitType;
    e.Parameters = e.Parameters.Union(
    new[]
    {
      new ResolvedParameter((p, i) => p.ParameterType == typeof(ILog), 
                            (p, i) => LogManager.GetLogger(t)),
    });
}
Run Code Online (Sandbox Code Playgroud)

附加到:

protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
{
    // Handle constructor parameters.
    registration.Preparing += OnComponentPreparing;

    // Handle properties.
    registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance);
}
Run Code Online (Sandbox Code Playgroud)