ray*_*enl 6 entity-framework unit-of-work repository-pattern
我在 .Net4.0 Web 表单(不是 MVC!)应用程序中使用 EF4.3.1。
我倾向于使用带有 IUnitOfWork 接口的存储库模式。但我想知道我是否遵循了最佳实践,尤其是因为我遵循的大多数示例都基于 MVC 应用程序。
我会说它只是一个小型网络应用程序,因此可能会影响解决方案的选择。
该解决方案目前有 3 个项目,Model、Logic 和 Site。模型包含 codefirst 实体和 IUnitOfWork 接口。逻辑包含存储库和服务层。站点显然包含网站、代码隐藏等。
我不使用任何第三方注入实用程序(ninject 等)。我用 IUnitOfWork 手动注入存储库,即
公共 BookingRepository(IUnitOfWork unitOfWork)
我不太清楚如何处理服务层,如果 IUnitOfWork 也存在于 Site 项目中,或者只存在于 Logic 和 Model 层中。
目前我将一个存储库和一个工作单元注入到一个服务中,即
公共预订服务(IUnitOfWork unitOfWork,IBookingRepository 存储库,IAppSettings appSettings)
但这意味着提交(保存到db)是在站点级别完成的,但我想知道是否应该在服务层完成。这也意味着,由于我的 IUnitOfWork 是在我的模型层中声明的,我还需要在我的站点中引用 Model。
我可以做什么更好?我做对了吗?哈哈
德米特里是对的。这是工作单元的示例实现。这里的好处是工作单元模式通过强制所有存储库共享单个数据库上下文类来协调多个存储库的工作。
这是开始了解如何一起使用这些模式的好资源。它对 MVC 和 Web Forms 开发都有效。在 ASP.NET MVC 应用程序中实现存储库和工作单元模式
public class UnitOfWork : IDisposable
{
private DbContext _context;
private PersonRepository _personRepository;
private CompanyRepository _companyRepository;
public UnitOfWork(DbContext context)
{
this._context = context;
}
public void Commit()
{
_context.SaveChanges();
}
// We lazy-load our repositories...
public PersonRepository PersonRepository
{
get
{
if (this._personRepository == null)
{
this._personRepository = new PersonRepository(context);
}
return _personRepository;
}
}
public CompanyRepository
{
get
{
if (this._companyRepository == null)
{
this._companyRepository = new CompanyRepository(context);
}
return _companyRepository;
}
}
//IDisposable implementation removed for brevity...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14613 次 |
最近记录: |