Unity Lifetime Managers & EF Data Context & # 8594; Best practice

Everything,

There have been many reports of Unity Lifetime Managers, but I have not yet found that someone claims a good rule of thumb: "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 my EF materials, a testing project, and an 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 notice that my context is not recreated with every new web request that I think I need (let me know if I am mistaken in this assumption). I find it difficult to analyze all the information from the sites listed below and read that many people create their own class called PerHttpRequestLifetimeManager to handle this.

What is really best practice?

+7
dependency-injection entity-framework asp.net-mvc-4 unity-container
source share
1 answer

Yes, usually you need one DbContext for the request.

The PerHttpRequestLifetimeManager, or a child container created for each request, are typical processing methods.

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

For more information, see Unity Dependency Injection Developer's Guide , Chapter 3, Injecting Dependencies with Unity .

+6
source share

All Articles