将耦合(依赖)对象注入(转换)为解耦(独立)对象的过程称为“依赖注入”。
依赖注入的类型
DI有四种类型-
构造函数注入
Setter注入
基于接口的注入
服务定位器注入
Getter和Setter注入使用默认的公共属性过程(如Gettter(get()
{})和Setter(set()
{}))来注入依赖项。
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"; } } public class BusinessLogicImplementation{ private IService _client; public IService Client{ get { return _client; } set { _client = value; } } public void SetterInj(){ Console.WriteLine("Getter and Setter Injection ==> Current Service : {0}", Client.ServiceMethod()); } }
BusinessLogicImplementation ConInjBusinessLogic = new BusinessLogicImplementation(); ConInjBusinessLogic.Client = new ClaimService(); ConInjBusinessLogic.SetterInj();