2014-10-03 57 views
0

我瞭解Repository模式,我發現許多代碼示例,但都是幾乎一樣的,所以我懷疑到這方面,例如這樣的設計:存儲庫模式接口 - 最佳實踐?

 public interface IRepository<T> 
    { 
     void Add(T entity); 
     void Update(T entity); 
     void Delete(T entity); 
     IList<T> GetAll(); 
    } 
    public interface IPostRepository 
    { 
     int GetComentCount(); 
    } 
    public class EFRepository<T>: IRepository<T> 
    { 
     public void Add(T entity){ /*implementation...*/ } 
     public void Update(T entity){ /*implementation...*/ } 
     public void Delete(T entity){ /*implementation...*/ } 
     public IList<T> GetAll(){ /*implementation...*/ } 
    } 
    public class PostRepository: EFRepository<Post>, IPostRepository 
    { 
     public int GetComentCount(){ /*implementation...*/ } 
    } 
    public class UnitOfWork: IUnitOfWork, IDisposable 
    { 
     IPostRepository PostRepository {get;} 
    } 

我可以這樣做:

IUnitOfWork UoW = new UnitOfWork(); 
    int nComments = UoW.PostRepository.GetComentCount(); 

,但不是這個:(顯然)

var collection = UoW.PostRepository.GetAll(); 

我該怎麼辦?我必須在UoW中創建另一個屬性並返回一個IRepository嗎? 我必須爲每個存儲庫創建一個沒有CRUD操作的接口(例如IPostRepository)嗎?必須一個具體的存儲庫一次從EFRepository類和接口繼承(例如:類PostRepository:EFRepository,IPostRepository {})?

您認爲如何?

PD:請原諒我可憐的英語。

+0

如果你讓'IPostRepository'繼承'IRepository',那麼它就會工作。 – 2014-10-03 15:16:55

+0

與@BenRobinson相同的評論。此外,如果您要採取最佳做法,請避免返回列表,返回ICollection ,IList ,IEnumerable ,IQueryable 或其他某個接口。 – braintechd 2014-10-03 15:18:31

+0

@braintechd你是對的我會更新該代碼。 – AiApaec 2014-10-03 15:28:38

回答

1

如果更改IPostRepository從IRepository繼承,你只是擴展接口表面,所以你不需要重新定義的所有方法。

例如,這種變化:

public interface IRepository<T> 
{ 
    void Add(T entity); 
    void Update(T entity); 
    void Delete(T entity); 
    IList<T> GetAll(); 
} 
public interface IPostRepository : IRepository<int> 
{ 
    int GetComentCount(); 
} 
public class EFRepository<T> : IRepository<T> 
{ 
    public void Add(T entity) { Console.WriteLine("Works"); } 
    public void Update(T entity) { /*implementation...*/ } 
    public void Delete(T entity) { /*implementation...*/ } 
    public IList<T> GetAll() { return null; } 
} 
public class PostRepository : EFRepository<int>, IPostRepository 
{ 
    public int GetComentCount() { return 0; } 
} 

public interface IUnitOfWork 
{ 

} 

public class UnitOfWork : IUnitOfWork, IDisposable 
{ 
    public IPostRepository PostRepository { get { return new PostRepository(); } } 

    public void Dispose() 
    { 
     throw new NotImplementedException(); 
    } 
} 

下面的代碼將打印作品

UnitOfWork t = new UnitOfWork(); 
t.PostRepository.Add(1); 

基本上,你的PostRepository不需要重新實現添加/更新/刪除方法因爲該接口契約已經存在於基類EFRepository中並且將被使用。 IPostRepository將強制您只提供擴展接口合同。

至於最佳做法,我不認爲這是一個很好的解決方案。我試着用繼承方法,但是我看到了有ReadOnly/Add/AddUpdate/etc的良好生產代碼。倉庫界面的組成。

P.S.我在這個例子中改變INT避免定義全新的類。

+0

謝謝。在我的情況下,IPostRepository應該是通用的(IPostRepository :IRepository ),因爲我在一個單獨的項目中沒有提及EF項目的接口。 – AiApaec 2014-10-03 16:41:28