Search code examples
.netdependency-injectionunity-containerioc-containerobject-lifetime

Will garbage collector recycle an object if the object's type was mapped with the TransientLifetimeManager in Unity?


Will garbage collector recycle an object if the object's type was mapped with the TransientLifetimeManager in Unity?

I assume the garbage collector will recycle the object. So, that makes me ask the following question: What is the difference between the TransientLifetimeManager and the ExternallyControlledLifetimeManager then? Both do not track the object lifetime.

In case the type registered with the TransientLifetimeManager won`t get recycled I have another question: Why did developers make such a decision? It seems unreasonable to preserve the type registered with the TransientLifetimeManager, since there are might be a lot of them created. And also once the object of the type registered with the TransientLifetimeManager is created the reference can be provided by the IoC container to the consumer only once, so, again no point in preserving the reference to the object.

NOTE

The question is not related to Unity3D at all. Please, keep it professional and do not edit the question if you do not know what it is about.


Solution

  • TransientLifetimeManager does not track lifietime, but it creates new instance per resolve. ExternallyControlledLifetimeManager does not track lifetime and creates only one instance. Container holds only weak reference to object, so after container disposing object will stay alive.

    More information in article and examples.