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

前端 未结 5 488
栀梦
栀梦 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:53

    This may be an older post, but I'd like to chime in.

    The idea that IOC of a logging system is overkill is short-sighted.

    Logging is a mechanism by which an application developer can communicate with other systems (event logs, flat files, a database, etc.), and each of these things is now an external resource upon which your application is dependent.

    How am I supposed to unit test my component's logging if my unit-tested code is now locked to a particular logger? Distributed systems often use loggers which log to centralize sources, not to flat files on the file system.

    Injecting a logger, to me, is no different than injecting a database connection API or an external web service. It is a resource which the application requires, and as such, should be injected, so you can test the component's usage of said resourceThe ability to mock said dependence, to test the output of my component independent of the logging recipient, is crucial to strong unit testing.

    And given that IOC containers make such injection child's play, it seems to me that NOT using IOC to inject the logger is no more valid an approach than doing so.

提交回复
热议问题