【问题标题】:Generic repository - IRepository<T> or IRepository通用存储库 - IRepository<T> 或 IRepository
【发布时间】:2009-12-05 20:50:16
【问题描述】:

我见过两种不同的创建通用存储库的方法。这两种方法有什么区别(优点和缺点)? 请忽略方法上的差异,因为我对

 public interface IRepository<T> where T : class

 public interface IRepository : IDisposable

在功能、灵活性、单元测试方面有什么不同...?我会得到什么或失去什么?
它们在依赖注入框架中的注册方式有什么不同吗?

选项 1

 public interface IRepository<T> where T : class
 {
       T Get(object id);
       void Attach(T entity);
       IQueryable<T> GetAll();
       void Insert(T entity);
       void Delete(T entity);
       void SubmitChanges();
 }

选项 2

 public interface IRepository : IDisposable
    {
        IQueryable<T> GetAll<T>();
        void Delete<T>(T entity);
        void Add<T>(T entity);
        void SaveChanges();
        bool IsDisposed();
    }

【问题讨论】:

    标签: c# linq generics repository


    【解决方案1】:

    最大的区别是IRepository&lt;T&gt; 绑定到单个类型,而IRepository 可能绑定到多个类型。哪一个是合适的在很大程度上取决于您的特定场景。

    一般来说,我发现IRepository&lt;T&gt; 更有用。在使用的时候非常清楚IRepository&lt;T&gt;的内容是什么(T)。另一方面,从给定的IRepository 中并不清楚其中包含什么。

    如果我必须存储多种类型的对象,我通常会创建一个 IRepository&lt;T&gt; 实例的映射。例如:Dictionary&lt;T,IRepository&lt;T&gt;&gt;

    【讨论】:

    • 当我的实体有非常不同的方法时,我不建议为每个实体实现 IRepository 因为每个实体都会有一个它可能根本不使用的方法的空实现。仅当您的实体有很多常用方法时才执行 IRepository,否则您的 Repository 类最终将包含空方法。
    • 我不认为空洞的方法像巨人一样危险,世界末日的太阳天赋。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    相关资源
    最近更新 更多