Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic repository - IRepository<T> or IRepository

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();     } 
like image 252
Robert Vuković Avatar asked Dec 05 '09 20:12

Robert Vuković


People also ask

What is Irepository for?

Basically, a repository allows you to populate data in memory that comes from the database in the form of the domain entities. Once the entities are in memory, they can be changed and then persisted back to the database through transactions.

What is a generic repository?

It is a data access pattern that prompts a more loosely coupled approach to data access. We create a generic repository, which queries the data source for the data, maps the data from the data source to a business entity, and persists changes in the business entity to the data source.

Is generic repository Antipattern?

A generic repository is a type that comprises of a set of generic methods for performing CRUD operations. However, it's just another anti pattern and is used frequently with Entity Framework to abstract calls to the data access layer.

Why would you implement a generic repository?

It reduces redundancy of code. It force programmer to work using the same pattern. It creates possibility of less error. If you use this pattern then it is easy to maintain the centralized data access logic.


1 Answers

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>>.

like image 177
JaredPar Avatar answered Sep 29 '22 04:09

JaredPar