English 中文(简体)
ASP.NET MVC-使用UnitOfWork
原标题:ASP.NET MVC - Using UnitOfWork

我目前正在开发一个由6层组成的网络应用程序:

  • Web (reference to ViewModels and Controllers)
  • ViewModels
  • Controllers
  • Services (reference to Data and Entities)
  • Data (reference to Entities)
  • Entities

我试图实现的是一个“UnitOfWork”模式,因此我有一个由DI为该作业注入的类,这使得当我完成数据库时,可以在控制器的actionresult中执行.commit()。

现在是我的问题。。。这个UnitOfWork类应该放在哪里?目前它在我的数据层中,但这需要控制器层引用数据层和服务层,这在我看来很奇怪。。。我应该将UnitOfWork类/接口移动到服务层并使用DI吗?

最佳回答

除非您在Data层中使用Repository模式,否则您是在浪费时间。

UoW的目的是处理多个存储库实例之间的更改,这可以通过以下方式完成:

  1. Unit of Work derives from the actual underlying context (DataContext - L2SQL, ObjectContext/EF)
  2. Repositories take a Unit of Work in their ctor.

工作单元做两件事:

  1. Have a Commit() method
  2. Expose the underlying object/entity set to the Repository.

设置这一切有点棘手,但一旦完成,流程应该是这样的:

  1. Controller get s DI ed a service and a unit of work (both via Interfaces)
  2. Controller calls method on a service ("CustomerServices.AddOrder()")
  3. Service calls method on Repository
  4. Repository calls "Add" method on "Order" object/entity set
  5. Controller commits Unit of Work

从本质上讲,每个层都在其构造函数中获取“下一层”的一个实例所有东西都应该是DI和接口驱动的。UoW不依赖任何东西,但存储库依赖它来持久化到“内部内存”(ORM),然后UoW“提交”将把更改推送到数据库(基本上封装了“SaveChanges”方法)。

由于工作单元是一个基础设施/持久性/数据库/事务性问题,因此它应该进入您的数据层。应仅由控制器引用。

问题回答

我实现了我的IUnitOfWork类,将其直接传递到我的MVC控制器中(通过Castle Windsor注入)。然后,我让我的控制器将它传递给它实例化的任何服务对象。

IUnitOfWork应该是数据层的接口。当请求进入控制器时,调用服务方法,如果您需要CRUD,则应该调用UnitOfWork。您可以通过调用Global.asax Request_Start中的UnitOfWork并在Request_End中提交工作来使用Session Per Request。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签