Skip to content

Instantly share code, notes, and snippets.

@derekgreer
Created July 22, 2011 22:48
Show Gist options
  • Save derekgreer/1100611 to your computer and use it in GitHub Desktop.
Save derekgreer/1100611 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>>();
public T Get<T>() {
return (T) Get(typeof (T));
}
public 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 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