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

c# – 如何使用使用泛型与依赖注入的存储库接口?

发布时间:2020-12-15 06:50:18 所属栏目:百科 来源:网络整理
导读:我正在尝试使用以下通用存储库接口进行DI和构造器注入: public interface IRepositoryTEntity : IDisposable where TEntity : class 问题是为了定义一个接口的实例,我必须提供这样的类类型: private IRepositoryPerson _personRepository; 这个问题是如果
我正在尝试使用以下通用存储库接口进行DI和构造器注入:
public interface IRepository<TEntity> : IDisposable where TEntity : class

问题是为了定义一个接口的实例,我必须提供这样的类类型:

private IRepository<Person> _personRepository;

这个问题是如果我使用DI(并且我使用Unity for IoC框架),那么我必须在我的构造函数中定义多个实例来获取我需要使用的所有存储库接口:

public MyClass(IRepository<Person> personRepository,IRepository<Orders> ordersRepository,IRepository<Items> itemsRepository,IRepository<Locations> locationsRepository)
{
  _personRepository = personRepository;
  _OrdersRepository = ordersRepository; 
  _itemsRepository = itemsRepository;
  _locationsRepository = locationsRepository;
}

问题:

这是可以吗?
>如果不是我失去了这个概念?
>即使这是正确的,Unity将注册接口与具体类型有什么关系?我已经做了,因为通用存储库强制我声明.

请帮我清除这一点,谢谢你的帮助!

解决方法

Is this OK?

当然.有个人偏好是否使用像你有的构造函数注入或属性注入.构造函数注入是更清洁的,因为您不必为构造函数提供很多参数,但它也更安全.

what’s the point of Unity to register Interface to concrete type

一个原因是,您可以对MyClass进行单元测试,而无需使用实际的数据库存储库.您可以“伪造”出存储库以返回硬编码的值进行测试.

(编辑:李大同)

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

    推荐文章
      热点阅读