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

单接口多实现的依赖注入优化方案咨询:批量创建不同类型机器实例

优化方案:简化批量机器创建与DI配置

针对你的需求,我们可以去掉冗余的双工厂实现,利用依赖注入的IEnumerable<T>注入特性,直接构建指定数量的机器集合,同时保持代码简洁性。

步骤1:添加机器类型标识

首先定义枚举区分机器类型,让每个IMachineService实现可以被识别:

public enum MachineType
{
    TypeA,
    TypeB
}

步骤2:改造IMachineService接口

为接口增加类型标识属性,方便后续匹配对应服务:

public interface IMachineService
{
    MachineType Type { get; }
    IMachine CreateMachine();
}

实现类示例:

public class MachineAService : IMachineService
{
    public MachineType Type => MachineType.TypeA;

    public IMachine CreateMachine() => new MachineA();
}

public class MachineBService : IMachineService
{
    public MachineType Type => MachineType.TypeB;

    public IMachine CreateMachine() => new MachineB();
}

步骤3:简化DI配置与集合构建

直接在DI注册时完成机器集合的创建,无需额外工厂类:

// 注册所有机器服务
services.AddScoped<IMachineService, MachineAService>();
services.AddScoped<IMachineService, MachineBService>();

// 构建并注册指定数量的机器集合(单例生命周期,可根据需求调整)
services.AddSingleton<IReadOnlyCollection<IMachine>>(sp =>
{
    var machineServices = sp.GetRequiredService<IEnumerable<IMachineService>>();
    var machines = new List<IMachine>();

    // 创建5个A型机器
    var typeAService = machineServices.First(s => s.Type == MachineType.TypeA);
    for (var i = 0; i < 5; i++)
    {
        machines.Add(typeAService.CreateMachine());
    }

    // 创建3个B型机器
    var typeBService = machineServices.First(s => s.Type == MachineType.TypeB);
    for (var i = 0; i < 3; i++)
    {
        machines.Add(typeBService.CreateMachine());
    }

    return machines.AsReadOnly();
});

步骤4:使用机器集合

在需要使用机器的类中,直接注入IReadOnlyCollection<IMachine>即可:

public class MachineManager
{
    private readonly IReadOnlyCollection<IMachine> _machines;

    public MachineManager(IReadOnlyCollection<IMachine> machines)
    {
        _machines = machines;
    }

    public void StartAllMachines()
    {
        foreach (var machine in _machines)
        {
            machine.Start();
        }
    }
}

方案优势

  • 移除了冗余的IMachineFactory和IMachineServiceFactory,减少代码复杂度
  • 利用DI原生的IEnumerable<T>注入,自动获取所有注册的机器服务实现
  • 机器数量配置直观,修改循环次数或扩展字典即可调整不同类型机器的数量
  • 集合生命周期可灵活配置(单例/作用域/瞬时),适配不同业务场景

内容的提问来源于stack exchange,提问作者H. Ivanov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:05:31