Context lifetime management in repository and unit of work pattern

人盡茶涼 提交于 2020-02-08 07:24:31

问题


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 -

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

How are you guys keeping managing your context:

Anything like this - http://www.west-wind.com/weblog/posts/2008/Feb/05/Linq-to-SQL-DataContext-Lifetime-Management

Or

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?


回答1:


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:

  • 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


来源:https://stackoverflow.com/questions/7457275/context-lifetime-management-in-repository-and-unit-of-work-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!