原为链接 https://www.cnblogs.com/ysmc/p/18794061
在上一个文章中,我们讲过 键控服务 服务,可惜的是这个需要 .NET 8 才能使用,那我们在 .NET 8 之前应该怎么找到我们需要的服务呢,本文给大家讲讲使用特性的方式
本人依旧秉承着短小精悍,废话不多,直接上代码!
起首,我们写一个特性,自界说特性需要继承 Attribute,并且我们给一个只能 get 的 public 的属性,用于后续获取指定服务使用- public class ServerKeyAttribute : Attribute
- {
- public string Key { get; }
- public ServerKeyAttribute(string key)
- {
- Key = key;
- }
- }
复制代码 随便界说一个接口- public interface ITestService
- {
- Task GetValue();
- }
复制代码 然后就是多写几个实现,并且使用上面的自界说特性- [ServerKey("Test1")]
- public class Test1Service : ITestService
- {
- public void GetValue()
- {
- Console.WriteLine("Test1");
- }
- }
- [ServerKey("Test2")]
- public class Test2Service : ITestService
- {
- public void GetValue()
- {
- Console.WriteLine("Test2");
- }
- }
- [ServerKey("Test3")]
- public class Test3Service : ITestService
- {
- public void GetValue()
- {
- Console.WriteLine("Test3");
- }
- }
复制代码 注册服务- builder.Services.AddTransient<ITestService, Test1Service>();
- builder.Services.AddTransient<ITestService, Test2Service>();
- builder.Services.AddTransient<ITestService, Test3Service>();
复制代码 末了我们简单点,在 Controller 中获取指定服务,因为我比较懒- 1 [HttpGet("GetServers")]
- 2 public async Task GetServers([FromServices] IEnumerable<ITestService> testServices)
- 3 {
- 4 foreach (var service in testServices)
- 5 {
- 6 var attributes = service.GetType().GetCustomAttributes(typeof(ServerKeyAttribute), false) as IEnumerable<ServerKeyAttribute>;
- 7 if (attributes != null && attributes.Any())
- 8 {
- 9 if (attributes.Any(x => x.Key == "Test2"))
- 10 {
- 11 service.GetValue();
- 12 }
- 13 }
- 14 }
- 15
- 16 await Task.CompletedTask;
- 17 }
复制代码 结果
好嘞,完事,是不是非常简单,非常感谢各位大佬的观看
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
|