Skip to content

Instantly share code, notes, and snippets.

@burkeholland
Forked from derekgreer/Monarchy.cs
Created July 23, 2011 01:20
Show Gist options
  • Save burkeholland/1100811 to your computer and use it in GitHub Desktop.
Save burkeholland/1100811 to your computer and use it in GitHub Desktop.
Monarchy Refactored
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Monarchy
{
public class ObjectFactory {
static readonly IDictionary<Type, Func<object>> Container = new Dictionary<Type, Func<object>>();
static readonly MethodInfo CreateObjectMethodInfo = typeof (ObjectFactory).GetMethod("Get");
public T Get<T>() {
Type t = typeof (T);
if (Container.ContainsKey(t)) return (T) Container[t]();
ConstructorInfo[] ctors = t.GetConstructors();
ConstructorInfo largestCtor = ctors.OrderBy(c => c.GetParameters().Length).First();
var args = new object[largestCtor.GetParameters().Length];
Array.ForEach(largestCtor.GetParameters(), p =>
{
MethodInfo mi = CreateObjectMethodInfo.MakeGenericMethod(new[] {p.ParameterType});
args[p.Position] = mi.Invoke(this, null);
});
return (T) Activator.CreateInstance(t, args);
}
public void Register<T>(Func<T> factory) where T : class {
Container[typeof (T)] = factory;
}
public void Register<T,TResolved>() {
Container[typeof (T)] = () => Get<TResolved>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment