2013-04-12 25 views
6

Tôi đã xem xét việc triển khai các mẫu này trong một dự án mà tôi đang làm việc. UoW có ngữ cảnh cơ sở dữ liệu và sau đó instantiates một số kho với bối cảnh đó. Câu hỏi của tôi là xử lý ngữ cảnh. Rất nhiều bài viết tôi đã thấy có kho lưu trữ là IDisposable và sau đó chúng bỏ đi ngữ cảnh. Điều này đã làm tôi bối rối không có kết thúc, tôi thiếu một cái gì đó hoặc (trong trường hợp của tôi) nên nó chỉ là UoW mà bố trí bối cảnh? Ngoài ra, tôi có nên triển khai IDisposable trên các kho lưu trữ của mình không?Đơn vị công việc, kho và IDisposable

Cảm ơn

Chris

Trả lời

9

Vâng, các đơn vị công việc cần thực hiện IDisposable và định đoạt bối cảnh, không phải là kho.

Đây là một ví dụ:

public interface IUnitOfWork : IDisposable 
{ 
    void Commit(); 
} 

public class EntityFrameworkUnitOfWork<TContext> : IUnitOfWork 
    where TContext : DbContext, new() 
{ 
    public EntityFrameworkUnitOfWork() 
    { 
     this.DbContext = new TContext(); 
     ConfigureContext(this.DbContext); 
    } 

    protected virtual void ConfigureContext(TContext dbContext) 
    { 
     dbContext.Configuration.ProxyCreationEnabled = false; 
     dbContext.Configuration.LazyLoadingEnabled = false; 
     dbContext.Configuration.ValidateOnSaveEnabled = false; 
    } 

    protected TContext DbContext { get; private set; } 

    public void Commit() 
    { 
     this.DbContext.SaveChanges();   
    } 

    public void Dispose() 
    { 
     this.Dispose(true); 
     GC.SuppressFinalize(this); 
    } 

    protected virtual void Dispose(bool disposing) 
    { 
     if (!disposing) 
     { 
      return; 
     } 

     if (this.DbContext == null) 
     { 
      return; 
     } 

     this.DbContext.Dispose(); 
     this.DbContext = null; 
    } 
}