原为链接 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 }
结果
好嘞,完事,是不是非常简单,非常感谢各位大佬的观看
来源链接:https://www.cnblogs.com/ysmc/p/18794061
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END
暂无评论内容