如何将构造函数中注入的多个接口合并为单个统一接口使用?
多接口合并解决方案
这个方案基于**门面模式(外观模式)**做接口聚合,完全兼容你现有设计,代码改造成本极低。
实现步骤
- 定义统一聚合接口,所有需要注入的服务作为接口属性暴露
public interface IApiServiceAggregate { // 现有服务属性 ISettingsService SettingsService { get; } ICustomerApiService CustomerApiService { get; } IProductApiService ProductApiService { get; } IProductPriceApiService ProductPriceApiService { get; } // 后续新增服务仅需在此处添加对应属性即可 }
- 实现聚合接口,在构造函数中注入所有对应服务完成赋值
public class ApiServiceAggregate : IApiServiceAggregate { public ISettingsService SettingsService { get; } public ICustomerApiService CustomerApiService { get; } public IProductApiService ProductApiService { get; } public IProductPriceApiService ProductPriceApiService { get; } public ApiServiceAggregate(ISettingsService settingsService, ICustomerApiService customerApiService, IProductApiService productApiService, IProductPriceApiService productPriceApiService) { SettingsService = settingsService; CustomerApiService = customerApiService; ProductApiService = productApiService; ProductPriceApiService = productPriceApiService; } }
- 在DI容器中注册聚合服务,以微软原生DI为例:
// 原有服务的注册保留,新增下面一行即可 services.AddSingleton<IApiServiceAggregate, ApiServiceAggregate>(); // 生命周期和你原有服务保持一致即可,Windows服务场景一般用Singleton/Scoped都可以
- 改造你的
CallBackService代码,仅注入聚合接口即可
#region Variables private readonly IApiServiceAggregate _serviceAggregate; private readonly SettingsDto _settings; private readonly Timer _timer; #endregion #region Constructor public CallBackService(IApiServiceAggregate serviceAggregate) { InitializeComponent(); _serviceAggregate = serviceAggregate; _settings = _serviceAggregate.SettingsService.Get(); _timer = new Timer(); } #endregion
后续使用时仅需通过_serviceAggregate.XXX调用对应服务的方法即可,原有调用逻辑几乎不需要修改。
方案优势
- 构造函数永远仅需注入1个参数,后续新增服务不用修改业务服务的构造函数签名
- 完全保留原有接口的单一职责,底层的
IClientServices、CustomerClient、各ApiService的实现不需要做任何改动 - 适配Windows服务后台运行的场景,服务生命周期和原有逻辑完全一致,没有额外副作用
- 扩展成本极低,新增服务只需要在聚合接口加属性、实现类加注入即可
内容的提问来源于stack exchange,提问作者kozyalcin
相关产品推荐
相关产品推荐

