Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

asp.net mvc - What is the best way to instantiate and dispose DbContext in MVC?

MVC 3 + EF 4.1

I'm choosing between two approaches to deal with DbContext:

  1. Instantiate in Application_BeginRequest, put it into HttpContext.Current.Items and dispose in Application_EndRequest.
  2. Create disposable UnitOfWork (kindof wrapper for DbContext) and start each controller action with using(var unitOfWork = new UnitOfWork()) { ... }

Share your experience please: Which one would you prefer? what are pros and cons for each approach?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would suggest you use a Dependency Injection framework. You can register your DbContext as per request

 container.RegisterType<MyDbContext>().InstancePerHttpRequest();

And inject it as a constructor parameter to the controller.

public class MyController : Controller
{
    public MyController(MyDbContext myDbContext)
    {
         _myDbContext = myDbContext;
    }
}

If the registered type implements IDisposable then the DI framework will dispose it when the request ends.

1st approach: It is much more cleaner to use ID framework than manually implementing it. Further all your requests may not need your UoW.

2nd approach: The controller should not know how to construct your UoW(DbContext). Purpose is not reduce the coupling between components.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...