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

在.Net Core中如何多次注册同一个接口并传入不同构造参数

解决方案

完全可以实现,不需要保留冗余的IInterface2,根据你使用的.NET版本可以选择以下两种方案:


方案1:.NET 8及以上版本,使用原生键控服务

这是最简便的实现方式,ASP.NET Core DI 从.NET 8开始原生支持同一个类型按不同键注册不同实例:

  1. 注册阶段:
// 同一个IInterface1接口,用不同键绑定不同连接字符串的实例
services.AddKeyedScoped<IInterface1>("Conn1", (sp, key) => new ServiceClass(ConnectionString1));
services.AddKeyedScoped<IInterface1>("Conn2", (sp, key) => new ServiceClass(ConnectionString2));
  1. 使用阶段,在需要注入的地方通过[FromKeyedServices]特性指定要获取的实例:
public class YourBusinessClass
{
    public YourBusinessClass(
        [FromKeyedServices("Conn1")] IInterface1 serviceWithConn1,
        [FromKeyedServices("Conn2")] IInterface1 serviceWithConn2)
    {
        // 两个实例分别对应不同的连接字符串配置
    }
}

方案2:.NET 7及更低版本,使用自定义工厂模式

低版本没有原生键控服务,可以通过自定义工厂封装实例创建逻辑,避免冗余接口:

  1. 定义工厂接口和实现:
public interface IServiceClassFactory
{
    IInterface1 GetInstance(string connectionType);
}

public class ServiceClassFactory : IServiceClassFactory
{
    public IInterface1 GetInstance(string connectionType)
    {
        return connectionType switch
        {
            "Conn1" => new ServiceClass(ConnectionString1),
            "Conn2" => new ServiceClass(ConnectionString2),
            _ => throw new ArgumentException("无效的连接类型", nameof(connectionType))
        };
    }
}
  1. 注册工厂到DI容器:
services.AddSingleton<IServiceClassFactory, ServiceClassFactory>();
  1. 使用阶段注入工厂,按需获取对应实例:
public class YourBusinessClass
{
    private readonly IInterface1 _serviceWithConn1;
    private readonly IInterface1 _serviceWithConn2;

    public YourBusinessClass(IServiceClassFactory factory)
    {
        _serviceWithConn1 = factory.GetInstance("Conn1");
        _serviceWithConn2 = factory.GetInstance("Conn2");
    }
}

补充说明

如果ServiceClass本身还有其他依赖需要从DI容器获取,只需要在工厂实现中注入IServiceProvider,在创建ServiceClass实例时从容器解析对应依赖传入即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:39:03