AsSingletonPerThread - How to destroy registered object instances

Issue #19 closed
Former user created an issue

If i register types in the Container with AsSingletonPerThread, then the resolving is working fine with one instance per threadid.

But what, if a worker thread is ready and will be destroyed? How can i make sure all object instances registered with this threadID will be destroyed too?

Comments (6)

  1. Stefan Glienke repo owner

    Unfortunately this is not possible right now. The instances will be destroyed when the Lifetimemanager gets destroyed (which is most likely at the shutdown of your application).

    The problem is that there is no reliable way of tracking when a thread is finished. One could check for the OnTerminate event but that only works with TThreads and not some external ones (like TExternalThread does not execute OnTerminate afaik).

    Another possibility could be to implement ReleaseInstance in TSingletonPerThreadLifetimeManager and free the instances there but that might not be consistent to how that method is supposed to work. It also would require more work on the Release methods that currently are only available on TContainer. And since that would have to be called in the consuming code you don't want to have the TContainer there. I would stay away from this because this might break code if ReleaseInstance actually destroys an instance that might be used in another class (dangling pointer problem).

    AsSingletonPerThread is only suggested to be used when you work with a thread pool where you don't create and destroy threads all the time during your application lifetime but reuse them. For other cases you might consider using AsTransient and holding to that instance in your thread (which then is the same as AsSingletonPerThread) but of course that only works if this is not a dependency that is resolved by the container because then the container might create more than one for each thread.

  2. Log in to comment