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?
Use the ContainerControlledLifetimeManager when you want to create a singleton instance. In the above example, we specified ContainerControlledLifetimeManager in the RegisterType() method. So, Unity container will create a single instance of the BMW class and inject it in all the instances of Driver .
A special lifetime manager which works like ContainerControlledLifetimeManager, except that in the presence of child containers, each child gets it's own instance of the object, instead of sharing one in the common parent.
RegisterType a type mapping with the container, where the created instances will use the given LifetimeManager. Namespace: Microsoft.Practices.Unity. Assembly: Microsoft.Practices.Unity (in Microsoft.Practices.Unity.dll)
Unity container is an open source IoC container for . NET applications supported by Microsoft. It is a lightweight and extensible IoC container. The source code for Unity container is available at https://github.com/unitycontainer/unity.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With