.NET CORE 通过依赖注入获取所有的的实现
先定义一个接口
1 /// <summary> 2 /// 支付接口 3 /// </summary> 4 public interface IPaymentService 5 { 6 7 /// <summary> 8 /// 支付类型 9 /// </summary> 10 public string PayType { get; } //这个字段是用来筛选的,可以没有,属于业务字段,用于演示 11 12 }
1 然后实现这个接口 2 3 /// <summary> 4 /// 微信支付实现 5 /// </summary> 6 public class WeChatPaymentService : IPaymentService 7 { 12 private readonly IHttpContextAccessor _httpContextAccessor; 13 14 public WeChatPaymentService( 15 IHttpContextAccessor httpContextAccessor ) 20 { 21 _httpContextAccessor = httpContextAccessor; 26 } 27
//赋值筛选字段 28 public string PayType => "wechat"; 29 }
1 调用的时候使用 IEnumerable<> 2 3 4 /// <summary> 5 /// 测试获取接口所有注入实现 6 /// </summary> 7 [Route("api/[controller]")] 8 [ApiController] 9 public class PayTestController : ControllerBase 10 { 11 private IEnumerable<IPaymentService> _paymentService; 12 13 public PayTestController(IEnumerable<IPaymentService> paymentService) 14 { 15 _paymentService = paymentService; 16 } 17 18 [HttpGet] 19 [Route("testPay")] 20 public async Task<IActionResult> testPay(string groupOrderNumber) 21 {
// 可以通过 FirstOrDefault 来进行筛选
// _paymentService 是所有实现的集合 22 var paymentService = _paymentService.FirstOrDefault(m => m.PayType == "wechat"); 24 return Ok(); 26 } 28 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?