88 lines
2.0 KiB
C#
88 lines
2.0 KiB
C#
|
|
using System;
|
||
|
|
using System.Collections.Generic;
|
||
|
|
|
||
|
|
namespace XCEngine.Rendering
|
||
|
|
{
|
||
|
|
public sealed class ContextContainer : IDisposable
|
||
|
|
{
|
||
|
|
private readonly Dictionary<Type, ContextItem> m_items =
|
||
|
|
new Dictionary<Type, ContextItem>();
|
||
|
|
private bool m_disposed;
|
||
|
|
|
||
|
|
public bool Contains<T>()
|
||
|
|
where T : ContextItem
|
||
|
|
{
|
||
|
|
return m_items.ContainsKey(typeof(T));
|
||
|
|
}
|
||
|
|
|
||
|
|
public T Create<T>()
|
||
|
|
where T : ContextItem, new()
|
||
|
|
{
|
||
|
|
ThrowIfDisposed();
|
||
|
|
T item = new T();
|
||
|
|
m_items[typeof(T)] = item;
|
||
|
|
return item;
|
||
|
|
}
|
||
|
|
|
||
|
|
public T Get<T>()
|
||
|
|
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<T>()
|
||
|
|
where T : ContextItem, new()
|
||
|
|
{
|
||
|
|
ThrowIfDisposed();
|
||
|
|
ContextItem item;
|
||
|
|
if (m_items.TryGetValue(
|
||
|
|
typeof(T),
|
||
|
|
out item))
|
||
|
|
{
|
||
|
|
return (T)item;
|
||
|
|
}
|
||
|
|
|
||
|
|
return Create<T>();
|
||
|
|
}
|
||
|
|
|
||
|
|
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));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|