Search code examples
dependency-injectioninversion-of-controlunity-container

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?


Solution

  • 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