Returning an instance from a pool

Dec 16, 2010 at 8:31 PM

Hi all

I am using HierarchicalLifetimeManager and CreateChildContainer to ensure that my dependencies are unique per request.  However one of these dependences is fairly expensive to create.  I don't want to change my code to provider an IExpensiveItemPool, I just want to stick to objects requiring IExpensiveItem.

So, is there a way in Unity that I can register IExpensiveItem so that I retrieve from a pool and return to the pool when the ChildContainer is disposed of/collected?

Dec 17, 2010 at 11:14 AM

Hello,

Not sure if it's exactly what you're looking for, but I built a simple pooled lifetime manager for Unity:

http://weblogs.asp.net/ricardoperes/archive/2010/12/01/pooled-lifetime-manager-for-unity.aspx

Regards,

RP

Dec 17, 2010 at 7:26 PM

How does your app know when the expensive item should be added back to the pool?

Dec 17, 2010 at 7:29 PM

It doesn't, that's not it's purpose. It just maintains a pool of N instances.

Dec 17, 2010 at 8:19 PM

So once the 10 items in the pool are used that's it? No item ever goes back into the pool?

Dec 17, 2010 at 10:57 PM

Yes, that's it... it creates up to N instances, and then each time a new instance is requested it returns one of these instances in round-robin. Basically, if you have a general-purpose lifetime manager, how would you "release" an object? The lifetime manager base class has no knowledge of releasing objects. One could use a child container to do that, on the other hand.

Any ideas?

RP

Dec 19, 2010 at 10:35 AM

Yes, I do have an idea which I will work on later today if I first get my current problem out of the way.  

I need to know though

  1. Are you using either a new or child container for each request (after which the instance should get returned)?
  2. Is this an ASP MVC app you are writing or something else?

     
Dec 19, 2010 at 5:43 PM
Edited Dec 19, 2010 at 5:43 PM

Here it is - I hope it is of use to you.

Dec 20, 2010 at 1:22 PM

Hello, Peter!

It's a nice solution!

Regards,

RP

Dec 20, 2010 at 1:28 PM

Be aware that when the pooled resource is created it will have dependencies injected, if it does have dependencies then these should always be transient or have container controlled lifetimes on the master container not the child.  Otherwise your pooled resource will be holding onto services created in a child container which has been disposed of.

I am trying to work out if I can implement IPooledResource.RetrievedFromPool(IUnityContainer container); so that I can fix up any references local to the requesting container.