using System; using System.Collections.Generic; namespace XCEngine.Rendering { public sealed class ContextContainer : IDisposable { private readonly Dictionary m_items = new Dictionary(); private bool m_disposed; public bool Contains() where T : ContextItem { return m_items.ContainsKey(typeof(T)); } public T Create() where T : ContextItem, new() { ThrowIfDisposed(); T item = new T(); m_items[typeof(T)] = item; return item; } public T Get() where T : ContextItem { ThrowIfDisposed(); ContextItem item; if (!m_items.TryGetValue( typeof(T), out item)) { throw new InvalidOperationException( "Context item is not available: " + typeof(T).FullName); } return (T)item; } public T GetOrCreate() where T : ContextItem, new() { ThrowIfDisposed(); ContextItem item; if (m_items.TryGetValue( typeof(T), out item)) { return (T)item; } return Create(); } public void Dispose() { if (m_disposed) { return; } foreach (ContextItem item in m_items.Values) { if (item != null) { item.Reset(); } } m_items.Clear(); m_disposed = true; } private void ThrowIfDisposed() { if (m_disposed) { throw new ObjectDisposedException( nameof(ContextContainer)); } } } }