SimpleContainer.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. namespace Caliburn.Micro.Core {
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Reflection;
  7. /// <summary>
  8. /// A simple IoC container.
  9. /// </summary>
  10. public class SimpleContainer {
  11. static readonly Type delegateType = typeof(Delegate);
  12. static readonly Type enumerableType = typeof(IEnumerable);
  13. readonly List<ContainerEntry> entries;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref = "SimpleContainer" /> class.
  16. /// </summary>
  17. public SimpleContainer() {
  18. entries = new List<ContainerEntry>();
  19. }
  20. SimpleContainer(IEnumerable<ContainerEntry> entries) {
  21. this.entries = new List<ContainerEntry>(entries);
  22. }
  23. /// <summary>
  24. /// Registers the instance.
  25. /// </summary>
  26. /// <param name = "service">The service.</param>
  27. /// <param name = "key">The key.</param>
  28. /// <param name = "implementation">The implementation.</param>
  29. public void RegisterInstance(Type service, string key, object implementation) {
  30. RegisterHandler(service, key, container => implementation);
  31. }
  32. /// <summary>
  33. /// Registers the class so that a new instance is created on every request.
  34. /// </summary>
  35. /// <param name = "service">The service.</param>
  36. /// <param name = "key">The key.</param>
  37. /// <param name = "implementation">The implementation.</param>
  38. public void RegisterPerRequest(Type service, string key, Type implementation) {
  39. RegisterHandler(service, key, container => container.BuildInstance(implementation));
  40. }
  41. /// <summary>
  42. /// Registers the class so that it is created once, on first request, and the same instance is returned to all requestors thereafter.
  43. /// </summary>
  44. /// <param name = "service">The service.</param>
  45. /// <param name = "key">The key.</param>
  46. /// <param name = "implementation">The implementation.</param>
  47. public void RegisterSingleton(Type service, string key, Type implementation) {
  48. object singleton = null;
  49. RegisterHandler(service, key, container => singleton ?? (singleton = container.BuildInstance(implementation)));
  50. }
  51. /// <summary>
  52. /// Registers a custom handler for serving requests from the container.
  53. /// </summary>
  54. /// <param name = "service">The service.</param>
  55. /// <param name = "key">The key.</param>
  56. /// <param name = "handler">The handler.</param>
  57. public void RegisterHandler(Type service, string key, Func<SimpleContainer, object> handler) {
  58. GetOrCreateEntry(service, key).Add(handler);
  59. }
  60. /// <summary>
  61. /// Unregisters any handlers for the service/key that have previously been registered.
  62. /// </summary>
  63. /// <param name = "service">The service.</param>
  64. /// <param name = "key">The key.</param>
  65. public void UnregisterHandler(Type service, string key) {
  66. var entry = GetEntry(service, key);
  67. if (entry != null) {
  68. entries.Remove(entry);
  69. }
  70. }
  71. /// <summary>
  72. /// Requests an instance.
  73. /// </summary>
  74. /// <param name = "service">The service.</param>
  75. /// <param name = "key">The key.</param>
  76. /// <returns>The instance, or null if a handler is not found.</returns>
  77. public object GetInstance(Type service, string key) {
  78. var entry = GetEntry(service, key);
  79. if (entry != null) {
  80. return entry.Single()(this);
  81. }
  82. if (service == null) {
  83. return null;
  84. }
  85. if (delegateType.IsAssignableFrom(service)) {
  86. var typeToCreate = service.GetGenericArguments()[0];
  87. var factoryFactoryType = typeof(FactoryFactory<>).MakeGenericType(typeToCreate);
  88. var factoryFactoryHost = Activator.CreateInstance(factoryFactoryType);
  89. var factoryFactoryMethod = factoryFactoryType.GetMethod("Create", new Type[] { typeof(SimpleContainer) });
  90. return factoryFactoryMethod.Invoke(factoryFactoryHost, new object[] { this });
  91. }
  92. if (enumerableType.IsAssignableFrom(service) && service.IsGenericType()) {
  93. var listType = service.GetGenericArguments()[0];
  94. var instances = GetAllInstances(listType).ToList();
  95. var array = Array.CreateInstance(listType, instances.Count);
  96. for (var i = 0; i < array.Length; i++) {
  97. array.SetValue(instances[i], i);
  98. }
  99. return array;
  100. }
  101. return null;
  102. }
  103. /// <summary>
  104. /// Determines if a handler for the service/key has previously been registered.
  105. /// </summary>
  106. /// <param name="service">The service.</param>
  107. /// <param name="key">The key.</param>
  108. /// <returns>True if a handler is registere; false otherwise.</returns>
  109. public bool HasHandler(Type service, string key) {
  110. return GetEntry(service, key) != null;
  111. }
  112. /// <summary>
  113. /// Requests all instances of a given type.
  114. /// </summary>
  115. /// <param name = "service">The service.</param>
  116. /// <returns>All the instances or an empty enumerable if none are found.</returns>
  117. public IEnumerable<object> GetAllInstances(Type service) {
  118. var entry = GetEntry(service, null);
  119. return entry != null ? entry.Select(x => x(this)) : new object[0];
  120. }
  121. /// <summary>
  122. /// Pushes dependencies into an existing instance based on interface properties with setters.
  123. /// </summary>
  124. /// <param name = "instance">The instance.</param>
  125. public void BuildUp(object instance) {
  126. var injectables = from property in instance.GetType().GetProperties()
  127. where property.CanRead && property.CanWrite && property.PropertyType.IsInterface()
  128. select property;
  129. foreach (var propertyInfo in injectables) {
  130. var injection = GetAllInstances(propertyInfo.PropertyType).ToArray();
  131. if (injection.Any()) {
  132. propertyInfo.SetValue(instance, injection.First(), null);
  133. }
  134. }
  135. }
  136. /// <summary>
  137. /// Creates a child container.
  138. /// </summary>
  139. /// <returns>A new container.</returns>
  140. public SimpleContainer CreateChildContainer() {
  141. return new SimpleContainer(entries);
  142. }
  143. ContainerEntry GetOrCreateEntry(Type service, string key) {
  144. var entry = GetEntry(service, key);
  145. if (entry == null) {
  146. entry = new ContainerEntry { Service = service, Key = key };
  147. entries.Add(entry);
  148. }
  149. return entry;
  150. }
  151. ContainerEntry GetEntry(Type service, string key) {
  152. if (service == null) {
  153. return entries.FirstOrDefault(x => x.Key == key);
  154. }
  155. if (key == null) {
  156. return entries.FirstOrDefault(x => x.Service == service && x.Key == null)
  157. ?? entries.FirstOrDefault(x => x.Service == service);
  158. }
  159. return entries.FirstOrDefault(x => x.Service == service && x.Key == key);
  160. }
  161. /// <summary>
  162. /// Actually does the work of creating the instance and satisfying it's constructor dependencies.
  163. /// </summary>
  164. /// <param name = "type">The type.</param>
  165. /// <returns></returns>
  166. protected object BuildInstance(Type type) {
  167. var args = DetermineConstructorArgs(type);
  168. return ActivateInstance(type, args);
  169. }
  170. /// <summary>
  171. /// Creates an instance of the type with the specified constructor arguments.
  172. /// </summary>
  173. /// <param name = "type">The type.</param>
  174. /// <param name = "args">The constructor args.</param>
  175. /// <returns>The created instance.</returns>
  176. protected virtual object ActivateInstance(Type type, object[] args) {
  177. var instance = args.Length > 0 ? System.Activator.CreateInstance(type, args) : System.Activator.CreateInstance(type);
  178. Activated(instance);
  179. return instance;
  180. }
  181. /// <summary>
  182. /// Occurs when a new instance is created.
  183. /// </summary>
  184. public event Action<object> Activated = delegate { };
  185. object[] DetermineConstructorArgs(Type implementation) {
  186. var args = new List<object>();
  187. var constructor = SelectEligibleConstructor(implementation);
  188. if (constructor != null)
  189. args.AddRange(constructor.GetParameters().Select(info => GetInstance(info.ParameterType, null)));
  190. return args.ToArray();
  191. }
  192. static ConstructorInfo SelectEligibleConstructor(Type type) {
  193. return (from c in type.GetConstructors().Where(c => c.IsPublic)
  194. orderby c.GetParameters().Length descending
  195. select c).FirstOrDefault();
  196. }
  197. class ContainerEntry : List<Func<SimpleContainer, object>> {
  198. public string Key;
  199. public Type Service;
  200. }
  201. class FactoryFactory<T> {
  202. public Func<T> Create(SimpleContainer container) {
  203. return () => (T)container.GetInstance(typeof(T), null);
  204. }
  205. }
  206. }
  207. }