将耦合(依赖)对象注入(转换)为解耦(独立)对象的过程称为“依赖注入”。
依赖注入的类型
DI有四种类型-
构造函数注入
Setter 注入
基于接口的注入
服务定位器注入
Interface Injection与Getter and Setter DI类似,该Getter和Setter DI使用默认的getter和setter,但是Interface Injection使用支持接口的一种显式的getter和setter来设置接口属性。
public interface IService{ string ServiceMethod(); } public class ClaimService:IService{ public string ServiceMethod(){ return "ClaimService is running"; } } public class AdjudicationService:IService{ public string ServiceMethod(){ return "AdjudicationService is running"; } } interface ISetService{ void setServiceRunService(IService client); } public class BusinessLogicImplementationInterfaceDI : ISetService{ IService _client1; public void setServiceRunService(IService client){ _client1 = client; Console.WriteLine("Interface Injection ==> Current Service : {0}", _client1.ServiceMethod()); } }
BusinessLogicImplementationInterfaceDI objInterfaceDI = new BusinessLogicImplementationInterfaceDI(); objInterfaceDI= new ClaimService(); objInterfaceDI.setServiceRunService(serviceObj);