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

后端 未结 9 952
别那么骄傲
别那么骄傲 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 15:52

    You could derive another type e.g. LoggableBusinessObject that takes a logger in its constructor. This means you only pass in the logger for objects that will use it:

    public class MyBusinessObject
    {
        private IDependency _dependency;
    
        public MyBusinessObject(IDependency dependency)   
        {   
            _dependency = dependency;   
        }   
    
        public virtual string DoSomething(string input)   
        {   
            // Process input   
            var info = _dependency.GetInfo();   
            var result = PerformInterestingStuff(input, info);   
            return result;   
        }   
    }
    
    public class LoggableBusinessObject : MyBusinessObject
    {
        private ILogger _logger;
    
        public LoggableBusinessObject(ILogger logger, IDependency dependency)
            : base(dependency)
        {
            _logger = logger;
        }
    
        public override string DoSomething(string input)
        {
            string result = base.DoSomething(input);
            if (result == "SomethingWeNeedToLog")
            {
                 _logger.Log(result);
            }
        }
    }
    

提交回复
热议问题