上下文生命周期管理的工作模式库和单位 [英] Context lifetime management in repository and unit of work pattern

查看:151
本文介绍了上下文生命周期管理的工作模式库和单位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有花纹的UnitOfWork实施库和共享的上下文。
我对这些仓库之上的服务层。具有多个服务。当过我实例化一个服务类 - 的UnitOfWork实例被创建

I have a repositories implemented with unitOfWork pattern and share a context. i have a service layer on top of these repositories. which has multiple services. When ever i instantiate a service class - unitOfWork instance is created.

但很多时候,这些服务的方法相互调用,有时共同的会话对象进行操作。这使得相同的实体的问题,通过多个上下文或更具体地被跟踪 -

But many times these services methods call each other and sometimes operate on common session objects. Which causes a problem of the same entity being tracked by multiple contexts or more specifically -

这是实体对象不能由的多个实例被引用
  IEntityChangeTracker。

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

怎么样你们保持管理上下文:

How are you guys keeping managing your context:

这样的事 -
http://www.west-wind.com/weblog/posts/2008/Feb/05/Linq-to-SQL-DataContext-Lifetime-Management

或者

我也看到,人们把他们的背景下的的HttpContext 并使用它每个HTTP调用/每用户?

i have also read that people are putting their context in HttpContext and using it per http call / per user?

什么是做到这一点的最好方法是什么?

What is the best way to do this?

推荐答案

通用方法是使用每个Http请求单个上下文。这种背景下您的服务之间共享,因为如果单个请求处理呼叫中服务彼此他们是最有可能在工作单部门运营。如果他们不工作的一个单元操作可以需要每个工作各单位新的上下文。

The common approach is using single context per Http request. This context is shared among your services because if services within single request processing call each other they are most probably operate in single unit of work. If they do not operate in single unit of work you can need a new context per each unit of work.

与存储在会话对象的第二个问题是不相关的上下文实例化。它涉及到与存储代理实体到会话,而不从上下文分离它的事实。为了解决这个问题,你必须:

The second problem with objects stored in session is not related to context instantiating. It is relating to the fact that you stored proxied entity into session without detaching it from the context. To solve this problem you must either:


  • 处置它被用来加载实体(或者实体余辉期间附着)的上下文之前存储在会话分离的实体。这可以通过 context.Entry完成(实体).STATE = EntityState.Detached

  • 使用关闭对存储在会话实体代理的创建context.Configuration.ProxyCreationEnabled = FALSE

  • Detach entity stored in session prior to disposing the context it was used to load the entity (or where entity was attached during persistence). This can be done by context.Entry(entity).State = EntityState.Detached
  • Turn off proxy creation for entities stored in session by using context.Configuration.ProxyCreationEnabled = false

这篇关于上下文生命周期管理的工作模式库和单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆