Dependency Injection vs Service Location

前端 未结 11 1368
梦如初夏
梦如初夏 2020-11-28 03:59

I am currently weighing up the advantages and disadvantages between DI and SL. However, I have found myself in the following catch 22 which implies that I should just use SL

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 04:39

    We've landed on a compromise: use DI but bundle top-level dependencies into an object avoiding refactoring hell should those dependencies change.

    In the example below, we can add to 'ServiceDependencies' without having to refactor all derived dependencies.

    Example:

    public ServiceDependencies{
         public ILogger Logger{get; private set;}
         public ServiceDependencies(ILogger logger){
              this.Logger = logger;
         }
    }
    
    public abstract class BaseService{
         public ILogger Logger{get; private set;}
    
         public BaseService(ServiceDependencies dependencies){
              this.Logger = dependencies.Logger; //don't expose 'dependencies'
         }
    }
    
    
    public class DerivedService(ServiceDependencies dependencies,
                                  ISomeOtherDependencyOnlyUsedByThisService                       additionalDependency) 
     : base(dependencies){
    //set local dependencies here.
    }
    

提交回复
热议问题