Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have seen two different approaches for creating generic repositories. What are differences between those two approaches (pros and cons) ? Please diregard difference in the methods because I am interested in difference between

 public interface IRepository<T> where T : class

and

 public interface IRepository : IDisposable

Is there any difference in functionality, flexibility, unit testing ... ? What will I get or lose ?
Is there any difference how they are registered in Dependency Injection frameworks ?

Option 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();
 }

Option 2

 public interface IRepository : IDisposable
    {
        IQueryable<T> GetAll<T>();
        void Delete<T>(T entity);
        void Add<T>(T entity);
        void SaveChanges();
        bool IsDisposed();
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
230 views
Welcome To Ask or Share your Answers For Others

1 Answer

The biggest difference is that IRepository<T> is bound to a single type while an IRepository is potentially bound to multiple types. Which one is appropriate is highly dependent upon your particular scenario.

Generally speaking I find IRepository<T> to be more useful. At the time of use it's extremely clear what the contents of IRepository<T> are (T). On the other hand it's not clear from a given IRepository what is contained inside of it.

In cases where I have to store multiple types of objects, I usually create a map of IRepository<T> instances. For instance: Dictionary<T,IRepository<T>>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...