Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the main difference between ContainerControlledLifetimeManager and HierarchicalLifetimeManager?

What is the general difference between ContainerControlledLifetimeManager and HierarchicalLifetimeManager? I know that ContainerControlledLifetimeManager represent singleton that is DI container will create a new instance for each type which needed dependency. I read useful article about Understanding Lifetime Managers. I compared hash codes of instances which ere created by container with different lifetime managers. I got the same instance for each request if I use ContainerControlledLifetimeManager, but I got a different hash codes when I use HierarchicalLifetimeManager. As it is written in the article, each child container will create it's own instance. I do not fully understand it. Will parent and child have the same instance or not? What will happen if I won't have any children? When I should use this lifetime manager? Please could you explain it to me?

like image 788
Joseph Katzman Avatar asked Feb 08 '17 14:02

Joseph Katzman


1 Answers

ContainerControlledLifetimeManager resolves a singleton instance of the registered type scoped to the lifetime of the container

HierarchicalLifetimeManager resolves a singleton instance of the registered type scoped to the lifetime of the container which performed the resolution (but not necessarily, the container where the type was registered)

If your application only makes use of a single container, there is no difference in behavior between the HierarchicalLifetimeManager and ContainerControlledLifetimeManager

However, if your application creates child containers per session / request and resolves using these child containers then you effectively get a singleton instance of the registered types per session / request

like image 168
user2321864 Avatar answered Sep 22 '22 18:09

user2321864