Which pattern to use for logging? Dependency Injection or Service Locator?

后端 未结 9 971
别那么骄傲
别那么骄傲 2021-01-31 15:51

Consider this scenario. I have some business logic that now and then will be required to write to a log.

interface ILogger
{
    void Log(string stuff);
}

inte         


        
9条回答
  •  庸人自扰
    2021-01-31 16:09

    My little rule of thumb:

    • If it's in a class library, use either constructor injection or property injection with a null-object pattern.

    • If it's in a main application, use the service locator (or singleton).

    I find this applies pretty well when using log4net. You don't want class libraries reaching out to things that might not be there, but in an application program, you know that the logger is going to be there, and libraries like log4net are based heavily around the service-location pattern.

    I tend to think of logging as something sufficiently static that it doesn't really need DI. It's extremely unlikely that I'll ever change the logging implementation in an application, especially since every logging framework out there is incredibly flexible and easy to extend. It's more important in class libraries when your library might need to be used by several applications which already use different loggers.

    YMMV, of course. DI is great but that doesn't mean everything needs to be DI'ed.

提交回复
热议问题