存储接口类型和类,将接口继承为对象以供以后使用

问题描述 投票:0回答:1

我正在尝试创建一个可以传入接口和继承该接口的类的类。稍后我将调用一个方法并使用接口和类来注册 Transient 服务。但我不知道如何存储类型。

这是我到目前为止得到的:

public sealed class Transient : AppFeatureBase, IAppFeatureBase
{
    private static readonly Dictionary<Type, object> _vals = [];

    public static void Add<TService, TImplementation>() where TService : class
                                                        where TImplementation : class, TService
    {
        _vals.Add(TService, TImplementation);
    }

    public static IServiceCollection Add(IServiceCollection services)
    {
        return services.AddTransient<??, ??>();
    }
}
c# asp.net-core generics middleware transient
1个回答
0
投票

我最终得到了这个:

public sealed class Transient(Type service, Type obj) : AppFeatureBase(Features.Transient), IAppFeatureBase
{
    public Type Interface => service;
    public Type Implementation => obj;
}

使用中:

new Transient(typeof(ILocalRepo), typeof(LocalRepo))

if (features.Exists(Features.Transient))
{
    foreach (Transient feat in features.Where(feat => feat.Type == Features.Transient))
    {
        builder.Services.AddTransient(feat.Interface, feat.Implementation);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.