default usage of childcontainers leaks memory

Apr 20, 2009 at 2:19 PM
Edited Apr 20, 2009 at 2:21 PM
Default usage of child containers causes your application to leak memory, because child containers are kept alive if the parent container is still alive, unless Dispose() is called on the child container.

UnityContainer.CreateChildContainer creates a new UnityContainer and passes the parent (itself) in the constructor.
The UnityContainer constructor adds a reference to this (the child container) to the LifeTimeContainer of the parent container:
Only when the child container is explicitely disposed, this reference is removed from the parent's LifeTimeContainer.

I suggest that the parent lifetimecontainer only holds a weak reference to the child containers, to avoid memory leaks.

The problem is reproducible as follows:
- create a new windows forms project (vb in my case).
- add references to unity
- create form with button, textbox and checkbox
- button starts the test, textbox shows number of childcontainers created, checkbox toggles the Dispose() call on childcontainer
- put following code in Button1_Click
      Dim count As Integer = 0
Dim parent As New UnityContainer
Dim child = parent.CreateChildContainer()
If CheckBox1.Checked Then
End If
count += 1
If count Mod 1000 = 0 Then
TextBox1.Text = count.ToString()
End If
- start project, click button, open process explorer
- watch the app take all your memory.

Oct 28, 2009 at 7:42 PM

This is by design. If you use child containers, you're responsible for disposing them, just like any other disposable object.

Oct 28, 2009 at 7:56 PM

Of course. What was i thinking?