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

无法定义类型时如何引用泛型对象?DI瞬态服务配置难题

解决方案

核心问题在于你当前的两个TransientItem泛型结构体缺少统一的非泛型契约,导致无法在不确定具体类型的场景下统一存储和调用它们的Add方法。可以通过以下步骤解决:

1. 定义非泛型接口

先创建一个非泛型接口,为所有服务注册项提供统一的调用入口:

public interface ITransientItem
{
    IServiceCollection Add(IServiceCollection services);
}

2. 让泛型结构体实现接口

修改两个TransientItem泛型结构体,实现上面定义的非泛型接口:

public struct TransientItem<TEntity> : ITransientItem where TEntity : class
{
    public readonly IServiceCollection Add(IServiceCollection services) => services.AddTransient<TEntity>();
}

public struct TransientItem<TInterface, TEntity> : ITransientItem 
    where TInterface : class
    where TEntity : class, TInterface
{
    public readonly IServiceCollection Add(IServiceCollection services) => services.AddTransient<TInterface, TEntity>();
}

3. 调整Transient类的存储逻辑

把Transient类中的集合和方法返回类型替换为非泛型的ITransientItem,这样就能兼容两种泛型的服务项:

public interface ITransient : IAppFeatureBase
{
    IEnumerable<ITransientItem> Get();
}

public sealed class Transient : AppFeatureBase, ITransient
{
    private readonly ICollection<ITransientItem> _items = new Collection<ITransientItem>();

    public Transient(params ITransientItem[] items) : base(Features.Transient)
    {
        // 修正原代码的错误:应该添加传入的items而非自身的空集合
        _items.AddRange(items);
    }

    public IEnumerable<ITransientItem> Get() => _items;
}

4. 修改服务注册遍历代码

现在遍历的时候直接处理ITransientItem即可,无需关心具体的泛型参数:

foreach(Transient trans in features.Where(feat => feat.Type == Features.Transient))
{
    foreach(ITransientItem item in trans.Get())
    {
        item.Add(builder.Services);
    }
}

额外说明

  • 原Transient构造函数中的_items.AddRange(_items)是明显错误,会导致没有实际服务项被添加,必须修正为_items.AddRange(items)。
  • 这种非泛型接口的方式具备扩展性,后续如果需要新增其他类型的服务注册项,只要实现ITransientItem接口,就能被现有逻辑统一处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 05:42:55