加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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:

>存储库实现没有默认构造函数
>因为它没有默认构造函数,所以我无法提供链接问题中给出的解决方案.
>尝试services.AddScoped(typeof(IRepository<>),…)我收到错误使用泛型类型’IRepostiory< TIdType,TEntityType>‘需要2个类型参数

解决方法

由于此问题仍未正确标记为 duplicate:注册Generic类的方法:
services.AddScoped(typeof(IRepository<,>),typeof(Repository<,>));

现在您可以通过以下方式解决它:

serviceProvider.GetService(typeof(IRepository<A,B>));
// or: with extensionmethod
serviceProvider.GetService<IRepository<A,B>>();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读