Castle Windsor Typed Factory does not leak without release

I am using Castle Windsor Typed Factory. In our registration code, it is configured in such a way that it can create the Transient component:

container.AddFacility<TypedFactoryFacility>(); container.Register(Component.For<IThingFactory>().AsFactory()); container.Register(Component.For<IThing>().ImplementedBy<TransientObject>().Named("TransientObject").LifeStyle.Transient); 

From my understanding, Windsor Castle Typed Factory documentation I thought that the Transient object should be released by the Factory type, otherwise Typed Factory will save the link to the object. I tried to prove this by writing a test that used the method described in https://stackoverflow.com/a/212619/2/ .

But, to my surprise, this did not actually work, meaning that although I did not release the transition object back to the factory, it could still be fixed by GC. I am worried that maybe my test is misleading, and there really is a leak.

So my question is: is my test wrong, or is this documentation wrong?

Here's the test:

 var factory = container.Resolve<IThingFactory>(); WeakReference reference = null; new Action(() => { var service = factory.GetTransientObject(); reference = new WeakReference(service, true); })(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.That(reference.Target, Is.Null, "reference should be null"); 
+5
source share
1 answer

The Windsor monitors Transient instances only if they have some problems with the failure. A typical example of a disconnect problem is that the class implements the IDisposable interface.

So, if IThing is Transient , and it does not implement IDisposable , and it has no other problems associated with the failure, then Windsor will NOT track it, and the garbage collector can / will delete IThing instances.

BUT (and this is big, but) , I suggest you never rely on this behavior. IThing may be changed by the developer, and it may become one-time in the future. Or it may cause another write-off problem. And suddenly a memory leak occurs. Therefore, a simple rule should be observed:

Each time an object is explicitly resolved by calling container.Resolve , it must be freed by calling container.Release . Also, at any time when an object is explicitly created using a typed factory, it must be explicitly destroyed by the printed factory. It does not matter if the object is temporary or not, take care of its life span. Always. The creator of the object (whether windsor or typed factory) is responsible for destroying the object.

Basically, @piotrwest was right in his comment. However, this answer aims to explain that this is not just about IDisposable - about problems with decommissioning ( IDisposable is just one of them).

This wonderful article explains more details.

+4
source

Source: https://habr.com/ru/post/1258943/


All Articles