如何将AutoFac连接到Common.Logging? [英] How to wire up AutoFac to Common.Logging?

查看:97
本文介绍了如何将AutoFac连接到Common.Logging?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的班级:

public class LoggedFoo
{
    private readonly ILog _logger;

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

    public DoStuff()
    {
        this._logger.Info(i => i("Doing stuff..."));
    }
}

其中一项业务要求是正在为某些功能生成日志,因此自然而然地我想模拟出ILog进行验证.

One of the business requirements is that logs are being generated for certain functions, so naturally I want to mock out the ILog to verify.

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

However, Common.Logging library supports type-based loggers, along the lines of:

var logger = LogManager.GetLogger<LoggedFoo>();

...或:

var logger = LogManager.GetLogger(typeof(LoggedFoo));

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

The problem is, we are using AutoFac for dependency injection, and I cannot figure out how to instantiate an ILog based upon the class that is being instantiated for injection.

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

How do I write this? I am using the latest Nuget version of AutoFac.

推荐答案

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

I can think on 2 ways to achieve it:(well sorry the hour is 1:50 am in my country...)

  1. 将您的ILog更改为ILog<T>,然后将其注册为打开通用.

  1. Change your ILog to ILog<T> and then register it as an Open Generic.

使用动态提供程序允许您根据上下文进行解析.

Use Dynamic-Providers which allows you to resolve with a context.

Autofac的网站上有一个示例,正是您要寻找的东西.

Autofac's website has an example which seems to be the exact thing you were looking for.

使用上下文解决依赖性:

Resolve the dependency with a context:

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

附加到:

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

    // Handle properties.
    registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance);
}

这篇关于如何将AutoFac连接到Common.Logging?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆