在Unity中使用LogManager.GetLogger

Pau*_*ell 5 log4net unity-container

鉴于此类:

class Foo
{
    readonly ILog log;

    public Foo(ILog log)
    {
        this.log = log;
    } 

    ...
}
Run Code Online (Sandbox Code Playgroud)

我想配置Unity注入ILog.这很简单:

container.RegisterInstance<ILog>(LogManager.GetLogger(typeof(XYZ)));
Run Code Online (Sandbox Code Playgroud)

但是我想LogManager.GetLogger用正在解析的父类型的类型进行Unity调用.

这很接近:

container.RegisterType<ILog>(new InjectionFactory((c, t, s) => LogManager.GetLogger(t)));
Run Code Online (Sandbox Code Playgroud)

t在这种情况下,类型是resolve(ILog),而不是为(Foo)解析对象的类型.

我知道我可以这样做:

container.RegisterType<Foo>(new InjectionFactory(c => new Foo(LogManager.GetLogger(typeof(Foo)));
Run Code Online (Sandbox Code Playgroud)

但是我不希望每次注册对象时都要添加那个疯狂的声明.

我知道这可以在Autofac中完成,我知道真正的答案不是首先使用Unity,但这可以做到吗?:)

Seb*_*ber 6

Unity可能不会给你一些其他容器提供的好东西,但我还没有找到你不能轻易添加的功能.

var container = new UnityContainer();
container.AddNewExtension<TrackingExtension>();
container.RegisterType<ILog>(
  new InjectionFactory((ctr, type, name) =>
    {
      var tracker = ctr.Resolve<ITracker>();
      var parentType = tracker.CurrentBuildNode.Parent.BuildKey.Type;
      return LogManager.GetLogger(parentType);
    }));
var sut = container.Resolve<UsesLog>();
Assert.AreEqual(typeof(UsesLog), sut.Log.Type);
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到TrackingExtension 的源代码.它位于TecX.Unity项目文件夹中.