Implementing Object Pooling

May 25, 2011 at 6:31 AM

Hi,

I've managed to implement object scopes using child containers, but how can I implement an Object Pool for a specific export?

Thanks!

May 25, 2011 at 1:13 PM
Edited May 25, 2011 at 3:44 PM

I assume you're referring to the concept of object pool as it exists in Spring.NET. MEF doesn't have something like that, but it isn't difficult to implement it yourself:

 

 

[Export(typeof(IFooPool))]
public class SimpleFooPool : IFooPool, IDisposable
{
	private List<Foo> pool = new List<Foo>();

        [Import]
	public IFooFactory FooFactory { get; set; }

	public Foo BorrowObject()
        {
		if (pool.Length > 0)
		{
			int lastIndex = pool.Length - 1;
			var lastObject = pool[lastIndex];
                        pool.RemoveAt(lastIndex);
			return lastObject;
		}
		else
		{
			return FooFactory.CreateInstance();
		}
	}

	public void ReturnObject(Foo foo)
	{
		pool.Add(foo);
	}

	public void Dispose()
	{
		foreach (var foo in pool)
		{
			foo.Dispose();
		}
	}
}

I'm oversimplifying a bit here - you should probably use ExportFactory<Foo> instead of writing your own IFooFactory, and dispose the ExportLifetimeContext<Foo> instead of Foo directly. You might also want to keep track of borrowed objects and limit the number of objects kept in the pool. But hopefully you get the idea.

May 25, 2011 at 2:03 PM

I didn't think about a custom ExportFactory... good idea thanks!