给定此类:

class Foo
{
    readonly ILog log;

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

    ...
}

我想配置Unity以注入(inject)ILog。这很容易:
container.RegisterInstance<ILog>(LogManager.GetLogger(typeof(XYZ)));

但是我想让Unity调用LogManager.GetLogger并解析父类型的类型。

这很接近:
container.RegisterType<ILog>(new InjectionFactory((c, t, s) => LogManager.GetLogger(t)));

但是在这种情况下,t是要解析的类型(ILog),而不是要为其解析对象的类型(Foo)。

我知道我可以这样做:
container.RegisterType<Foo>(new InjectionFactory(c => new Foo(LogManager.GetLogger(typeof(Foo)));

但是我不想每次注册对象时都必须添加疯狂的声明。

我知道这可以在Autofac中完成,并且我知道真正的答案不是一开始就使用Unity,但是可以这样做吗? :)

最佳答案

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

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

关于log4net - 在Unity中使用LogManager.GetLogger,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8576842/

10-14 04:42