qidao123.com技术社区-IT企服评测·应用市场

标题: 依赖注入接口多实现如何获取指定服务 [打印本页]

作者: 民工心事    时间: 2025-3-26 16:36
标题: 依赖注入接口多实现如何获取指定服务
原为链接 https://www.cnblogs.com/ysmc/p/18794061
  在上一个文章中,我们讲过 键控服务 服务,可惜的是这个需要 .NET 8 才能使用,那我们在 .NET 8 之前应该怎么找到我们需要的服务呢,本文给大家讲讲使用特性的方式
  本人依旧秉承着短小精悍,废话不多,直接上代码!
起首,我们写一个特性,自界说特性需要继承 Attribute,并且我们给一个只能 get 的 public 的属性,用于后续获取指定服务使用
  1. public class ServerKeyAttribute : Attribute
  2. {
  3.     public string Key { get; }
  4.     public ServerKeyAttribute(string key)
  5.     {
  6.         Key = key;
  7.     }
  8. }
复制代码
随便界说一个接口
  1. public interface ITestService
  2. {
  3.     Task GetValue();
  4. }
复制代码
然后就是多写几个实现,并且使用上面的自界说特性
  1. [ServerKey("Test1")]
  2. public class Test1Service : ITestService
  3. {
  4.     public void GetValue()
  5.     {
  6.         Console.WriteLine("Test1");
  7.     }
  8. }
  9. [ServerKey("Test2")]
  10. public class Test2Service : ITestService
  11. {
  12.     public void GetValue()
  13.     {
  14.         Console.WriteLine("Test2");
  15.     }
  16. }
  17. [ServerKey("Test3")]
  18. public class Test3Service : ITestService
  19. {
  20.     public void GetValue()
  21.     {
  22.         Console.WriteLine("Test3");
  23.     }
  24. }
复制代码
注册服务
  1. builder.Services.AddTransient<ITestService, Test1Service>();
  2. builder.Services.AddTransient<ITestService, Test2Service>();
  3. builder.Services.AddTransient<ITestService, Test3Service>();
复制代码
末了我们简单点,在 Controller 中获取指定服务,因为我比较懒
  1. 1 [HttpGet("GetServers")]
  2. 2 public async Task GetServers([FromServices] IEnumerable<ITestService> testServices)
  3. 3 {
  4. 4     foreach (var service in testServices)
  5. 5     {
  6. 6         var attributes = service.GetType().GetCustomAttributes(typeof(ServerKeyAttribute), false) as IEnumerable<ServerKeyAttribute>;
  7. 7         if (attributes != null && attributes.Any())
  8. 8         {
  9. 9             if (attributes.Any(x => x.Key == "Test2"))
  10. 10             {
  11. 11                 service.GetValue();
  12. 12             }
  13. 13         }
  14. 14     }
  15. 15
  16. 16     await Task.CompletedTask;
  17. 17 }
复制代码
结果

好嘞,完事,是不是非常简单,非常感谢各位大佬的观看

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 qidao123.com技术社区-IT企服评测·应用市场 (https://dis.qidao123.com/) Powered by Discuz! X3.4