如何使用属性在 C# 中实现依赖注入?
将耦合(依赖)的对象注入(转换)为解耦(独立)的对象的过程称为依赖注入。
依赖注入的类型
有四种类型的 DI −
构造函数注入
Setter 注入
基于接口的注入
服务定位器注入
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();
广告