Using LogManager.GetLogger with Unity

后端 未结 3 1679
时光说笑
时光说笑 2021-02-06 13:22

Given this class:

class Foo
{
    readonly ILog log;

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

    ...
}

I\'d like to con

3条回答
  •  轮回少年
    2021-02-06 13:41

    Unity might not give you all the goodies some of the other containers offer but I have yet to find a feature you can't easily add.

    var container = new UnityContainer();
    container.AddNewExtension();
    container.RegisterType(
      new InjectionFactory((ctr, type, name) =>
        {
          var tracker = ctr.Resolve();
          var parentType = tracker.CurrentBuildNode.Parent.BuildKey.Type;
          return LogManager.GetLogger(parentType);
        }));
    var sut = container.Resolve();
    Assert.AreEqual(typeof(UsesLog), sut.Log.Type);
    

    You can find the source code for the TrackingExtension here. Its located in the TecX.Unity project folder.

提交回复
热议问题