again about log4net and Unity IOC config

后端 未结 2 1242
北恋
北恋 2021-01-01 01:42

I\'ve bumped through a few of these questions laying around various sites and the answers seem to be spun by l4n officianados toward the value of the lightweight wrapper tha

相关标签:
2条回答
  • 2021-01-01 02:10
    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.

    0 讨论(0)
  • 2021-01-01 02:31

    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.

    0 讨论(0)
提交回复
热议问题