如何存储接口及实现类类型,用于后续注册Transient服务?
解决方案
首先,你当前的存储结构无法正确适配需求,Dictionary<Type, object>不能精准存储接口与实现类的类型映射,应该改用Dictionary<Type, Type>来保存服务类型(接口)和对应的实现类类型的配对关系。
修正后的完整代码如下:
public sealed class Transient : AppFeatureBase, IAppFeatureBase { // 存储服务类型与实现类型的映射关系 private static readonly Dictionary<Type, Type> _serviceMappings = []; public static void Add<TService, TImplementation>() where TService : class where TImplementation : class, TService { // 将泛型参数对应的具体类型存入字典 _serviceMappings.Add(typeof(TService), typeof(TImplementation)); } public static IServiceCollection Add(IServiceCollection services) { // 遍历所有类型映射,批量注册Transient服务 foreach (var mapping in _serviceMappings) { services.AddTransient(mapping.Key, mapping.Value); } return services; } }
关键修正说明:
- 存储结构调整:把原有的
_vals改为_serviceMappings,类型替换为Dictionary<Type, Type>,明确存储的是两个Type对象的映射。 - 泛型Add方法优化:通过
typeof(TService)和typeof(TImplementation)获取实际类型,正确存入字典。 - 服务注册实现:遍历字典,调用
AddTransient的非泛型重载(接受两个Type参数),完成所有服务的批量注册。
使用示例:
// 添加接口与实现类的映射 Transient.Add<IMyService, MyService>(); Transient.Add<IAnotherService, AnotherService>(); // 在服务配置环节注册所有Transient服务 builder.Services.Add(Transient.Add(builder.Services));
内容的提问来源于stack exchange,提问作者SteinTech
相关产品推荐
相关产品推荐

