c# – 如何添加通用依赖注入
发布时间:2020-12-15 08:04:56 所属栏目:百科 来源:网络整理
导读:使用只读api服务并利用泛型将操作打包到基于约定的过程中. 存储库界面: public interface IRepositoryTIdType,TEntityType where TEntityType:class { TaskEntityMetadataTIdType GetMetaAsync();} 存储库实现: public class RepositoryTIdType,TEntityTyp
使用只读api服务并利用泛型将操作打包到基于约定的过程中.
存储库界面: public interface IRepository<TIdType,TEntityType> where TEntityType:class { Task<EntityMetadata<TIdType>> GetMetaAsync(); } 存储库实现: public class Repository<TIdType,TEntityType> : IRepository<TIdType,TEntityType> where TEntityType:class { public Repository(string connectionString) { // initialization } public async Tas<EntityMetadata<TIdType>> GetMetaAsync() { // implementation } } 在Startup.cs中 – >配置服务: services.AddSingleton<IRepository<int,Employee>> ( p=> new Repository<int,Employee>(connectionString)); services.AddSingleton<IRepository<int,Department>> ( p=> new Repository<int,Department>(connectionString)); // and so on 控制器: public class EmployeeController : Controller { public EmployeeController(IRepository<int,Employee> repo) {//stuff} } 我目前正在重复ConfigureServices中所有类型的实体类型的存储库实现.有没有办法让这个通用呢? services.AddSingleton<IRepository<TIdType,TEntityType>> ( p=> new Repository<TIdType,TEntityType>(connectionString)); 那么在控制器构造函数中调用可以自动获取相关的存储库吗? 更新1:不是duplicate: >存储库实现没有默认构造函数 解决方法
由于此问题仍未正确标记为
duplicate:注册Generic类的方法:
services.AddScoped(typeof(IRepository<,>),typeof(Repository<,>)); 现在您可以通过以下方式解决它: serviceProvider.GetService(typeof(IRepository<A,B>)); // or: with extensionmethod serviceProvider.GetService<IRepository<A,B>>(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |