.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 }
复制代码

 

posted @   亲爱的老王哥  阅读(65)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示