网站首页 全球最实用的IT互联网站!

人工智能P2P分享Wind搜索发布信息网站地图标签大全

当前位置:诺佳网 > 软件工程 > 后端开发 > .Net >

依赖注入接口多实现如何获取指定服务

时间:2025-03-26 16:36

人气:

作者:admin

标签:

导读:原为链接#160;https://www.cnblogs.com/ysmc/p/18794061 在上一个文章中,我们讲过#160;键控服务 服务,可惜的是这个需要 .NET 8 才能使用,那我们在 .NET 8 之前应该怎么找到我们需要的服务呢,本文...

原为链接 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

温馨提示:以上内容整理于网络,仅供参考,如果对您有帮助,留下您的阅读感言吧!
相关阅读
本类排行
相关标签
本类推荐

CPU | 内存 | 硬盘 | 显卡 | 显示器 | 主板 | 电源 | 键鼠 | 网站地图

Copyright © 2025-2035 诺佳网 版权所有 备案号:赣ICP备2025066733号
本站资料均来源互联网收集整理,作品版权归作者所有,如果侵犯了您的版权,请跟我们联系。

关注微信