[英]MVC Repository Pattern - disposing multiple repositories?
在我的應用程序中,我嘗試使用此ASP.NET指南來應用存儲庫模式,但不使用通用存儲庫和工作單元。
與我有關的事情正在處理。 目前,我的應用程序使用標准的Dispose()
控制器方法來Dispose()
DbContext
:
LibraryContext db = new LibraryContext();
//
...
//
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
但是如何處置多個儲存庫? 例如,我有三個: bookRepository
, userRepository
和collectionRepository
。 然后,我應該將它們全部放入方法中嗎?
protected override void Dispose(bool disposing)
{
if (disposing)
{
bookRepository.Dispose();
userRepository.Dispose();
collectionRepository.Dispose();
}
base.Dispose(disposing);
}
這是正確的方法嗎? 謝謝你的回答。
您可以創建基礎存儲庫,並由其他存儲庫擴展。 在基本存儲庫的ctor中,您可以初始化DbContext類,當要處置時,可以調用base.Dispose。 應該是這樣的:
public class BaseRepository<T> where T : BaseEntityWithId, new()
{
//Represent the context of the database.
public DbContext myContext { get; set; }
//Represent a virtual table of the database.
protected IDbSet<T> DbSet { get; set; }
//Represents base constructor of the base repository.
public BaseRepository()
{
this.myContext = new Context();
this.DbSet = this.Context.Set<T>();
}
public IObjectContextAdapter GetObjectContextAdapter()
{
return (IObjectContextAdapter)this.Context;
}
public virtual void Dispose()
{
if (this.Context != null)
{
this.Context.Dispose();
}
}
}
如果您真的不想為一個Dispose()方法創建基礎存儲庫,則應按1對其進行處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.