如何设置 Unity 容器来创建模拟/真实记录器实例
我现在很困惑,也许不明白真正的问题。
我有一个需要记录器实例来记录错误数据的对象。
例如
public class CommonFileSaver : IFileSaver
{
private static ILog _log = LogManager.GetLogger();
.....
}
我想测试日志记录过程。而我目前的决定是使用 ILog 接口的模拟。
此时我决定使用Unity来解决依赖关系。
所以该行
ILog _log = LogManager.GetLogger();
看起来像这样:
ILog _log = Resolver.Instance.Resolve<ILoger>();
问题是如何设置 Unity 容器以使用 LogManager 工厂返回 ILog 对象的新实例。
谢谢。
PS ILog 是 log4net 接口,现在整个日志记录都是使用 log4net 实现的。
I am confused right now, and maybe does not understand the real problem.
I have an object which require logger instance to log error data.
for example
public class CommonFileSaver : IFileSaver
{
private static ILog _log = LogManager.GetLogger();
.....
}
I wish to test the logging process. And my current decission is to use the mock of the ILog interface.
At this point I have decided to use Unity to resolve dependencies.
So the line
ILog _log = LogManager.GetLogger();
will look something like
ILog _log = Resolver.Instance.Resolve<ILoger>();
The question is how to setup the Unity container to return me new instance of the ILog object using LogManager factory.
Thank you.
P.S. ILog is the log4net interface, and the whole logging thing is implemented using log4net right now.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许设计上不正确,但是在Unity中使用工厂是可能的......
Maybe it is not correct in design, but using factory is possible in Unity...
这里的问题是你没有遵循好莱坞原则。静态工厂方法和单例不太适合依赖注入。您应该更改代码以注入 ILog 工厂:
The problem here is that you're not following the Hollywood principle. Static factory methods and singletons don't fit well with dependency injection. You should change your code, to inject your ILog factory:
您可以为 log4net 编写一个包装器(无论如何,这是一个好主意)。包装器将负责使用 log4net 工厂方法创建实例,并且还将确保调用“Configure”方法。
如果您编写包装器,您可能需要考虑这个 信息。
You could write a wrapper for log4net (something which imho is a good idea anyway). The wrapper would take care of creating the instances by using the log4net factory method and it would also make sure that the "Configure" method is called.
If you write a wrapper you might want to consider this information.
如果您想要实现的目标是使用模拟 ILog 测试日志记录过程,那么我建议您还模拟
LogManager
并在GetLogger
上设置期望code> 以便它将返回模拟 ILog。If the goal of what you are trying to achieve is to test the logging process with a mock ILog when I would suggest that you also mock the
LogManager
and set up an expectation on theGetLogger
so that it will return the mock ILog.