How to inject dependency to static class

前端 未结 2 515
滥情空心
滥情空心 2020-12-06 17:06

I\'ve been making simple logger class with DI but I have some problem and question.

There is a problem. If I make a logger class with DI. I should use it like this w

2条回答
  •  借酒劲吻你
    2020-12-06 18:07

    It doesn't make sense to use dependency injection (DI) with a static class. Instead of DI, simply add an initialization method to your static class and pass in the dependency.

    public static class LogService
    {
        private static ILoggable _logger;
    
        public static ILoggable Logger
        {
            get
            {
                 return _logger;
            }
        }
    
        public static InitLogger(ILoggable logger)
        {
             _logger = logger;
        }
    }
    

    To use the logger, just make sure to call InitLogger() first:

    LogService.InitLogger(new FileLogger());
    LogService.Logger.WriteLine("message");
    

提交回复
热议问题