You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何配置依赖注入,将IDictionary<string, IFooService>注入构造函数?

如何在.NET中注入IDictionary<string, IFooService>到构造函数

你已经注册了IFooService的两个实现,现在只需把这些实例封装成IDictionary<string, IFooService>并注册到依赖注入容器即可,以下是两种可行方案:

方案一:直接硬编码匹配实例与键

在Program.cs的服务注册代码中,添加字典的工厂注册逻辑:

// 保留你已有的服务注册
s.AddTransient<IFooService, AFooService>();
s.AddTransient<IFooService, BFooService>();

// 注册IDictionary<string, IFooService>
s.AddTransient<IDictionary<string, IFooService>>(serviceProvider =>
{
    // 获取所有已注册的IFooService实例
    var allFooServices = serviceProvider.GetServices<IFooService>();
    
    return new Dictionary<string, IFooService>
    {
        { "A", allFooServices.First(s => s is AFooService) },
        { "B", allFooServices.First(s => s is BFooService) }
    };
});

当MyClass的构造函数请求IDictionary<string, IFooService>时,容器会执行这个工厂方法,返回包含指定键值对的字典。

方案二:通过特性标记实现灵活匹配(推荐)

如果后续可能新增更多IFooService实现,硬编码判断类型会不够灵活,可以给每个实现类添加自定义特性来标记键:

  1. 定义特性类:
[AttributeUsage(AttributeTargets.Class)]
public class FooServiceKeyAttribute : Attribute
{
    public string Key { get; }
    public FooServiceKeyAttribute(string key) => Key = key;
}
  1. 给服务实现类添加特性:
[FooServiceKey("A")]
public class AFooService : IFooService
{
    // 类实现代码
}

[FooServiceKey("B")]
public class BFooService : IFooService
{
    // 类实现代码
}
  1. 在Program.cs中注册字典:
s.AddTransient<IFooService, AFooService>();
s.AddTransient<IFooService, BFooService>();

s.AddTransient<IDictionary<string, IFooService>>(serviceProvider =>
{
    var allFooServices = serviceProvider.GetServices<IFooService>();
    
    return allFooServices.ToDictionary(
        service => 
        {
            var keyAttr = service.GetType().GetCustomAttribute<FooServiceKeyAttribute>();
            if (keyAttr == null)
            {
                throw new InvalidOperationException($"服务类型 {service.GetType().Name} 未标记FooServiceKeyAttribute");
            }
            return keyAttr.Key;
        },
        service => service
    );
});

这种方式无需修改工厂代码,新增服务时只需给类添加特性即可自动加入字典。

内容的提问来源于stack exchange,提问作者EnenDaveyBoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 05:35:29