Skip to content

Instantly share code, notes, and snippets.

@burkeholland
Created July 25, 2011 16:22
Show Gist options
  • Save burkeholland/1104501 to your computer and use it in GitHub Desktop.
Save burkeholland/1104501 to your computer and use it in GitHub Desktop.
All Static
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Monarchy {
public class ObjectFactory {
static readonly IDictionary<Type, object> Container = new Dictionary<Type, object>();
public static T Get<T>() {
return (T) Get(typeof (T));
}
public static object Get(Type type) {
if (Container.ContainsKey(type)) return Container[type];
ConstructorInfo[] ctors = type.GetConstructors();
ConstructorInfo largestCtor = ctors.OrderByDescending(c => c.GetParameters().Length).First();
var args = new object[largestCtor.GetParameters().Length];
Array.ForEach(largestCtor.GetParameters(), p => { args[p.Position] = Get(p.ParameterType); });
return Activator.CreateInstance(type, args);
}
public static void Register(object instance) {
Container[instance.GetType()] = instance;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment