port from perforce
This commit is contained in:
70
aiwaz/Aiwaz.Common/ObjectFactory.cs
Normal file
70
aiwaz/Aiwaz.Common/ObjectFactory.cs
Normal file
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Aiwaz.Common
|
||||
{
|
||||
public class ObjectFactory
|
||||
{
|
||||
private Dictionary<Type, Type> m_Patterns = new Dictionary<Type, Type>();
|
||||
private Dictionary<Type, Dictionary<string, object>> m_StoredObjects = new Dictionary<Type, Dictionary<string, object>>();
|
||||
|
||||
public void RegisterPattern<O>()
|
||||
{
|
||||
var patternObject = typeof(O);
|
||||
var patternInterface = patternObject.GetInterface("I" + patternObject.Name);
|
||||
m_Patterns.Add(patternInterface, patternObject);
|
||||
}
|
||||
|
||||
public void RegisterPattern<I, O>()
|
||||
{
|
||||
m_Patterns.Add(typeof(I), typeof(O));
|
||||
}
|
||||
|
||||
public T CreateInstance<T>(params object[] args)
|
||||
{
|
||||
var creationType = m_Patterns.First(argPattern => argPattern.Key == typeof(T)).Value;
|
||||
Type[] creationArguments = null;
|
||||
if (args != null && args.Length > 0)
|
||||
creationArguments = args.Select(arg => arg.GetType()).ToArray();
|
||||
|
||||
var constructor = creationType.GetConstructor(creationArguments == null ?
|
||||
System.Type.EmptyTypes : creationArguments);
|
||||
|
||||
var construct = (T)constructor.Invoke(args);
|
||||
return construct;
|
||||
}
|
||||
|
||||
public T CreateNamedInstance<T>(string argName, params object[] args)
|
||||
{
|
||||
var construct = CreateInstance<T>(args);
|
||||
|
||||
var storage = m_StoredObjects.FirstOrDefault(type => type.Key == typeof(T)).Value;
|
||||
if (storage == null)
|
||||
{
|
||||
m_StoredObjects.Add(typeof(T), new Dictionary<string, object>());
|
||||
storage = m_StoredObjects.FirstOrDefault(type => type.Key == typeof(T)).Value;
|
||||
}
|
||||
storage.Add(argName, construct);
|
||||
|
||||
return construct;
|
||||
}
|
||||
|
||||
public T FindNamedInstance<T>(string argName)
|
||||
{
|
||||
var storage = m_StoredObjects.FirstOrDefault(type => type.Key == typeof(T)).Value;
|
||||
if (storage == null || !storage.ContainsKey(argName))
|
||||
return default(T);
|
||||
return (T)storage[argName];
|
||||
}
|
||||
|
||||
public void RemoveNamedInstance<T>(string argName)
|
||||
{
|
||||
var storage = m_StoredObjects.FirstOrDefault(type => type.Key == typeof(T)).Value;
|
||||
if (storage == null)
|
||||
return;
|
||||
storage.Remove(argName);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user