Should logging infrastructure be injected when using IoC/DI if logging facade is used?

前端 未结 5 561
栀梦
栀梦 2021-02-02 07:30

I am using Autofac as my IoC and from everything I have read on topic of DI teaches to use \"constructor injection\" to explicitly expose class dependencies... However, I am als

5条回答
  •  爱一瞬间的悲伤
    2021-02-02 07:52

    In many applications, because logging is needed across your entire application's architecture, injecting it everywhere clutters and complicates your code. A static reference to a Logger object is fine, as long as your Logger has some sort of Attach(ILoggerService) mechanism where you attach logging services for the running environment. Your static Logger then stores these in a collection for use when performing the logging commands.

    When bootstrapping an application at runtime, attach the logging targets your application requires (file, database, webservice, etc).

    When performing automated tests, you can choose to not to use logging by not attach anything (by default). If you want to analyse the logging of your system under test you attach your own ILoggerService instance/subsitute/mock when you set up the test.

    A static Logger such as this should have minimal performance issues and no unintended consequences while avoiding code clutter by bypassing the need for dependency injection.

    It must be stated that you shouldn't take this static object approach for every object in your architecture; logging is a special case. Generally using static objects in your codebase makes maintenance and testing difficult and should be avoided.

提交回复
热议问题