Manage the lifetime of dbContext

a 夏天 提交于 2020-01-10 14:08:17

问题


I would like to tie the lifetime of a dbContext to the lifetime of a session, to - for example - be able to commit or abandon changes on a group of mutations on the dbcontext over multiple requests.

Are there any other (better?) ways to accomplish this? If no, what would be a suitable mechanism to create and dispose of the contexts? I am thinking about static hashtables with cleanup on session end, but maybe I'm doing it All Wrong. I am also thinking about the idea of only holding on to those contexts that have to do work over multiple requests, and keeping the rest per action. Any advice?


回答1:


You can use IoC(Inversion of Control) containers to manage the lifetime of DBContext such as StructureMap with following steps :

  1. Install nuget package for MVC 4 : http://nuget.org/packages/StructureMap.MVC4

  2. Read quick start : http://docs.structuremap.net/QuickStart.htm

  3. Set scope of your DBContext : http://docs.structuremap.net/Scoping.htm

Also you can use the combination of Repository and Unit Of Work Patterns for commit or abandon changes on a group of mutations on the dbcontext over multiple requests.




回答2:


This question is answered fairly elegantly in the following SO post:

StructureMap CacheBy InstanceScope.HttpSession not working

Essentially, the magic comes from the following code (adapted for your question and the newer syntax for StructureMap):

ObjectFactory.Initialize(factory => {
    factory.For<MyContext>()
           .CacheBy(InstanceScope.HttpSession)
           .Use(new MyContext(_myConnectionString));
});

Then - in your controller, simply create an instance of the object by using:

var db = ObjectFactory.GetInstance<MyContext>();

Because your IoC (Inversion of Control) set-up via StructureMap has configured the instances to be scoped to HttpSession, you should retrieve the same context each time as long as the session is the same.

However - bear in mind that with DbContext objects, in particular, this is usually a very poor idea - as you are mixing a state-tracking object with a stateless environment, and can easily get yourself into a state where a bad transaction or an object which is in an odd state can stop you from doing any further database calls until you refresh your session.

DbContext objects are generally designed to be extremely lightweight and disposable. It's fully ok to let them drop out of scope and die basically as soon as you're done with them.




回答3:


It's not a good idia to give DbContext live with the session.

  1. When you have more request it will load some part of data to the context from the DB which make context more big , that means memory issues,

  2. And you will not have updated data compared to DbContet per a request in the context because another user (another session) may have updated the data which you already have loaded to the context.

Caching Entity Framework DbContexts per request

And read this for your options ,

Asp.Net MVC and Session




回答4:


Typically in this scenario you need keep changes in temporary store(like session or cookie or database). When you need to save result or view new data you get old data and changes and build new object. Changes can be stored as new object or sequence of actions. Be carfule when apply changes, data conflict may be occure. Of cource use Context\Request




回答5:


In theory you can store a context into the Session dictionary that you can access in each controller. However you might have some threading problem, because at time you store it you are in a different thread than when you retrieve it. If context doesnt use threadstatic varaibles this might work (but I am not sure of this), otherwise not. In any case this is bad design ...none in the web do this...why do you want to store context? You can re-create it at a cheap price in ths subsequent http request. If you need to track changes of properties there are other ways more adequate to the web.



来源:https://stackoverflow.com/questions/13067793/manage-the-lifetime-of-dbcontext

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