在Unity中使用LogManager.GetLogger [英] Using LogManager.GetLogger with Unity
问题描述
提供此类:
class Foo
{
readonly ILog log;
public Foo(ILog log)
{
this.log = log;
}
...
}
我想配置Unity以注入ILog.很简单:
I'd like to configure Unity to inject ILog. That's easy:
container.RegisterInstance<ILog>(LogManager.GetLogger(typeof(XYZ)));
但是我想让Unity调用LogManager.GetLogger
并解析父类型的类型.
But I'd like to make Unity call LogManager.GetLogger
with the type of the parent type being resolved.
这很接近:
container.RegisterType<ILog>(new InjectionFactory((c, t, s) => LogManager.GetLogger(t)));
但是在这种情况下,t
是要解析的类型(ILog
),而不是要解析对象的类型(Foo
).
But t
in this case is the type being resolved (ILog
), not the type that the object is being resolved for (Foo
).
我知道我可以做到:
container.RegisterType<Foo>(new InjectionFactory(c => new Foo(LogManager.GetLogger(typeof(Foo)));
但是我不想每次注册对象时都必须添加疯狂的声明.
But I don't want to have to add that crazy declaration every time I register an object.
我知道这可以在Autofac中完成,并且我知道真正的答案不是一开始就使用Unity,但是可以这样做吗? :)
I know this can be done in Autofac, and I know the Real Answer is not to use Unity in the first place, but can this be done? :)
推荐答案
Unity可能不会为您提供其他一些容器提供的所有好处,但是我还没有找到您无法轻松添加的功能.
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<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);
您可以在 ="em> TrackingExtension 此处找到源代码.它位于 TecX.Unity 项目文件夹中.
You can find the source code for the TrackingExtension here. Its located in the TecX.Unity project folder.
这篇关于在Unity中使用LogManager.GetLogger的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!