Is it a good practice to have logger as a singleton?

后端 未结 8 939
迷失自我
迷失自我 2020-12-12 12:08

I had a habit to pass logger to constructor, like:

public class OrderService : IOrderService {
     public OrderService(ILogger logger) {
     }
}

8条回答
  •  天命终不由人
    2020-12-12 12:19

    Good question. I believe in most projects logger is a singleton.

    Some ideas just come to my mind:

    • Use ServiceLocator (or an other Dependency Injection container if you already using any) which allows you to share logger across the services/classes, in this way you can instantiate logger or even multiple different loggers and share via ServiceLocator which is obviously would be a singleton, some kind of Inversion of Control. This approach gives you much flexibility over a logger instantiation and initialization process.
    • If you need logger almost everywhere - implement extension methods for Object type so each class would be able to call logger's methods like LogInfo(), LogDebug(), LogError()

提交回复
热议问题