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
679 views
in Technique[技术] by (71.8m points)

entity framework - Unity Lifetime Managers & EF Data Context --> Best Practice

All,

There has been a lot of posts about Unity Lifetime Managers but I have yet to find someone state a good rule of thumb for "in these cases you should always use X". Let me describe my application, I have an ASP.NET MVC 4 Web Application. I have a Visual Studio solution containing 3 projects, my 'Core' project which has all of my EF stuff, a testing project, and the MVC Web Project. I am using Unity for dependency injection and have the following code right now:

// Context
container.RegisterType<IDatabaseFactory, DatabaseFactory>(
    new ContainerControlledLifetimeManager();
container.RegisterType<UnitOfWork>(
    new ContainerControlledLifetimeManager());

However, I'm noticing that my context is not recreated with every new web request which is what I think I would want (let me know if I'm wrong in that assumption). I'm having a hard time analyzing all of the information from the sites listed below and have read about a lot of people creating their own class named PerHttpRequestLifetimeManager to handle this.

What truly is the best practice here?

  1. Understanding Lifetime Managers by Microsoft's Developer Network - http://msdn.microsoft.com/en-us/library/ff660872(v=PandP.20).aspx
  2. MVC DI & Unity with Lifetime Manager via CodeProject - http://www.codeproject.com/Articles/424743/MVC-DI-Unity-with-Lifetime-Manager
  3. ASP.NET MVC Tip: Dependency Injection with Unity Application Block via Shiju Varghese's Blog - http://weblogs.asp.net/shijuvarghese/archive/2008/10/24/asp-net-mvc-tip-dependency-injection-with-unity-application-block.aspx
  4. MVC, EF - DataContext singleton instance Per-Web-Request in Unity via Stack Overflow - MVC, EF - DataContext singleton instance Per-Web-Request in Unity
  5. Inject same DataContext instance across several types with Unity via Stack Overflow - Inject same DataContext instance across several types with Unity
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yes, you usually want one DbContext per request.

A PerHttpRequestLifetimeManager or child container created on every request are the typical ways this is handled.

The latest release of Unity introduces the Unity bootstrapper for ASP.NET MVC which has a new built-in lifetime manager: PerRequestLifetimeManager.

You can read more in the Developer's Guide to Dependency Injection Using Unity chapter 3, Dependency Injection with Unity.


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

...