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:
<appSettings> <!-- format is TypeName + "PoolSize" --/> <add key="ISomeTypePoolSize" value="10" /> </appSettings> <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <container> <register type="ISomeType" mapTo="SomeType"> <lifetime type="PooledLifetimeManager`1[[ISomeType]]"/> </register> </container> </unity>
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); } else { ++index; 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); } } }