again about log4net and Unity IOC config

感情迁移 提交于 2019-11-30 09:57:54
David Keaveny

Would using the InjectionFactory in Unity 2 help? (see this question). Then your configuration code would look something like this:

IUnityContainer container = new UnityContainer();
container.RegisterType<ILog>(new InjectionFactory(factory => LogManager.GetLogger()));

Then you retrieve the logger with the usual call to Resolve():

ILog logger = container.Resolve<ILog>();
logger.Log(Level.Debug, "Hello world");

You might also be able to configure the lifetime of the logger to be ContainerControllerLifetimeManager as well, to make it a singleton instance, but I haven't verified that yet.

AllenM
ILog logger = container.Resolve<ILog>();
logger.Log(Level.Debug, "Hello world");

does indeed work.

However, if you have a property for a logger on a class, and want to inject this logger instance to it, that will not work AFAICT. I guess I may be off target, but I am trying to reuse the logger instance in a new context. This may just be undoable, so I may have to give up on injecting it and just add the line

ILog logger = container.Resolve<ILog>();

to every class, which gives me an outcome that only seems marginally different than instantiating it in every class....

I was hoping that

private ILog Logger {get;set;} 

could just be injected but that doesn't seem to work at all, since all through log4net everything is done via interfaces and the concrete logger is hiding behind the curtain with the Wizard of Oz.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!