Development With A Dot

Blog on development in general, and specifically on .NET



My Friends

My Links

Permanent Posts

Portuguese Communities

Pooled Lifetime Manager for Unity

A pooled lifetime manager for Unity. Creates new objects up to a maximum size and returns them in round-robin sequence. Default pool size is set to 5, but you can override it in the appSettings section with a key:

		<!-- format is TypeName + "PoolSize" --/>
		<add key="ISomeTypePoolSize" value="10" />
	<unity xmlns="">
			<register type="ISomeType" mapTo="SomeType">
				<lifetime type="PooledLifetimeManager`1[[ISomeType]]"/>

Here's the code:

public class PooledLifetimeManager<T> : SynchronizedLifetimeManager where T : class
	private static List<T> list = null;
	private static Int32 index = -1;

	static PooledLifetimeManager()
		Int32 capacity = 5;

		Int32.TryParse(ConfigurationManager.AppSettings [ String.Concat(typeof(T).Name, "PoolSize") ] ?? capacity.ToString(), out capacity);

		list = new List<T>(capacity);

	protected override Object SynchronizedGetValue()
		if (list.Capacity > list.Count)
			return (null);

			if (index == list.Capacity)
				index = 0;

			return (list [ index ]);

	protected override void SynchronizedSetValue(Object newValue)
		if (list.Count < list.Capacity)
			list.Add(newValue as T);

Bookmark and Share


cubud said:

How does it know when to return an item to the pool?

# December 17, 2010 3:18 PM

Ricardo Peres said:

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

# December 17, 2010 3:29 PM

jgauffin said:

list.Add(newValue as T);

That would add null items if object is of wrong type. It's better to use "(T)newValue" to get the exception earlier.

SynchronizedGetValue indicates that the LifeTimeManager should be thread safe. yours isn't

# January 4, 2011 2:19 PM