自从我使用Entity Framework以来,已经有一段时间了,我遵循了有关UnitOfWork模式的在线教程。我对为什么DataContext是公共UnitOfWork构造函数的参数感到困惑。这意味着,如果我在应用程序的另一层中使用UnitOfWork,则另一层必须了解DataContext。这似乎不是很好的关注点分离。我想念什么吗?
UnitOfWork:
public class UnitOfWork : IUnitOfWork
{
private readonly PurchasingDataContext _context;
public UnitOfWork(PurchasingDataContext context)
{
_context = context;
Items = new ItemRepository(_context);
Manufacturers = new LabelerRepository(_context);
Quotes = new QuoteRepository(_context);
Vendors = new VendorRepository(_context);
Contacts = new ContactRepository(_context);
}
public IItemRepository Items { get; private set; }
public ILabelerRepository Manufacturers { get; private set; }
public IQuoteRepository Quotes { get; private set; }
public IVendorRepository Vendors { get; private set; }
public IContactRepository Contacts { get; private set; }
public int Complete()
{
return _context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
接口:
public interface IUnitOfWork : IDisposable
{
IContactRepository Contacts { get; }
IItemRepository Items { get; }
ILabelerRepository Manufacturers { get; }
IQuoteRepository Quotes { get; }
IVendorRepository Vendors { get; }
int Complete();
}
我对为什么在本教程中
DataContext
是public
UnitOfWork
构造函数的参数感到困惑。
我首先要问您为什么要在UnitOfWork中创建和公开这些存储库。具有负责一个工作单元和所有存储库所有权的单一类违反了“单一责任原则”。您的IUnitOfWork公开了调用者可能需要或不需要的每个单个存储库,这违反了接口隔离原则。