我正在尝试创建一个可以传入接口和继承该接口的类的类。稍后我将调用一个方法并使用接口和类来注册 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<??, ??>();
}
}
我最终得到了这个:
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);
}
}