In the Unity PerThreadLifetimeManager documentation, I read that: "This lifetime manager does not dispose the instances it holds". Ref.: http://msdn.microsoft.com/en-us/library/ff647854.aspx
So, if I am using a ThreadPool, does it mean that objects resolved using Unity on a Thread of the ThreadPool will not get disposed at the end of the work done in that thread before being returned to the pool?
Any pattern or ideas how I can ensure that 开发者_如何转开发the objects do get disposed & I get a clean thread from the thread pool?
Thanks!
It depends on what type of lifetime manager. The PerThreadLifetimeManager maintains a single instance per thread. There are six provided types of lifetime managers, but that doesn't mean you can't make your own if they don't suit you.
Seems like you want the TransientLifetimeManager which provides a new instance per call. You can call Resolve within your worker thread, use the instance, and dispose of it before the method exits.
I'm not sure you could create a lifetime manager that would, somehow automatically, know that your thread has completed execution. The best way to ensure that would happen is to create a method wrapper that 1) gets the instance from Unity (using the TransientLifetimeManager), executes an Action<T> (your actual worker method) passing in the instance, and then disposes of that instance before exiting. Then you would execute your code by passing it to this wrapper, which is run on a worker thread. You'd only have to write your Resolve() and Dispose() code once and reuse it everywhere.
精彩评论