ServiceContainer.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. namespace Wayne.Lib
  5. {
  6. class ServiceContainer : IServiceContainer
  7. {
  8. private readonly IServiceLocator parentServiceLocator;
  9. private readonly Dictionary<ServiceKey , object> services;
  10. private bool isDisposed;
  11. public ServiceContainer()
  12. {
  13. services = new Dictionary<ServiceKey, object>();
  14. }
  15. public ServiceContainer(IServiceLocator parentServiceLocator)
  16. {
  17. services = new Dictionary<ServiceKey, object>();
  18. this.parentServiceLocator = parentServiceLocator;
  19. }
  20. public void RegisterService<TServiceImplementation>()
  21. {
  22. AssertContainerIsNotDisposed();
  23. var instance = (TServiceImplementation)TryCreate(typeof(TServiceImplementation));
  24. RegisterService(instance);
  25. }
  26. public void RegisterService<TServiceImplementation>(string serviceId)
  27. {
  28. AssertContainerIsNotDisposed();
  29. var instance = (TServiceImplementation)TryCreate(typeof(TServiceImplementation), serviceId);
  30. RegisterService(instance, serviceId);
  31. }
  32. public void RegisterService<TServiceContract>(TServiceContract serviceInstance)
  33. {
  34. RegisterService(serviceInstance, string.Empty);
  35. }
  36. public void RegisterService<TServiceContract>(TServiceContract serviceInstance, string serviceId)
  37. {
  38. AssertContainerIsNotDisposed();
  39. services[new ServiceKey(typeof(TServiceContract), serviceId )] = serviceInstance;
  40. }
  41. public void RegisterService<TServiceContract>(ObjectConstructor<IServiceLocator, TServiceContract> constructorMethod)
  42. {
  43. AssertContainerIsNotDisposed();
  44. var serviceInstance = constructorMethod.Invoke(this);
  45. services[new ServiceKey(typeof(TServiceContract))] = serviceInstance;
  46. }
  47. public void RegisterService<TServiceContract>(ObjectConstructor<IServiceLocator, TServiceContract> constructorMethod, string serviceId)
  48. {
  49. AssertContainerIsNotDisposed();
  50. var serviceInstance = constructorMethod.Invoke(this);
  51. services[new ServiceKey(typeof(TServiceContract), serviceId)] = serviceInstance;
  52. }
  53. public void RegisterService<TServiceContract, TServiceImplementation>()
  54. where TServiceImplementation : TServiceContract
  55. where TServiceContract : class
  56. {
  57. AssertContainerIsNotDisposed();
  58. var instance = (TServiceImplementation)TryCreate(typeof(TServiceImplementation));
  59. if ((object)instance == null) //Cast to object to get rid of warning
  60. throw new ServiceContainerException(typeof(TServiceImplementation), "Could not create implementation");
  61. RegisterService<TServiceContract>(instance);
  62. }
  63. public void RegisterService<TServiceContract, TServiceImplementation>(string serviceId)
  64. where TServiceImplementation : TServiceContract
  65. where TServiceContract : class
  66. {
  67. AssertContainerIsNotDisposed();
  68. var instance = (TServiceImplementation)TryCreate(typeof(TServiceImplementation), serviceId);
  69. if ((object)instance == null) //Cast to object to get rid of warning
  70. throw new ServiceContainerException(typeof(TServiceImplementation), "Could not create implementation");
  71. RegisterService<TServiceContract>(instance, serviceId);
  72. }
  73. public TServiceContract GetService<TServiceContract>()
  74. {
  75. return (TServiceContract)GetService(typeof(TServiceContract));
  76. }
  77. public TServiceContract GetService<TServiceContract>(string serviceId)
  78. {
  79. return (TServiceContract)GetService(typeof(TServiceContract), serviceId);
  80. }
  81. public object GetService(Type serviceType)
  82. {
  83. return GetService(serviceType, string.Empty);
  84. }
  85. public object GetService(Type serviceType, string serviceId)
  86. {
  87. AssertContainerIsNotDisposed();
  88. object service;
  89. if (!services.TryGetValue(new ServiceKey(serviceType, serviceId), out service))
  90. {
  91. if (parentServiceLocator != null)
  92. return parentServiceLocator.GetService(serviceType, serviceId);
  93. throw ServiceContainerException.CreateNotFoundException(serviceType);
  94. }
  95. return service;
  96. }
  97. public TServiceContract GetServiceOrDefault<TServiceContract>(CreateDefaultService<TServiceContract> func, string serviceId)
  98. {
  99. AssertContainerIsNotDisposed();
  100. object service;
  101. Type serviceType = typeof(TServiceContract);
  102. var key = new ServiceKey(serviceType, serviceId);
  103. if (!services.TryGetValue(key, out service))
  104. {
  105. if (parentServiceLocator != null)
  106. return parentServiceLocator.GetServiceOrDefault(func, serviceId);
  107. return func();
  108. }
  109. return (TServiceContract)service;
  110. }
  111. public TServiceContract GetServiceOrDefault<TServiceContract>(CreateDefaultService<TServiceContract> func)
  112. {
  113. return GetServiceOrDefault(func, string.Empty);
  114. }
  115. public T CreateInstance<T>(params object[] additionalObjects) where T : class
  116. {
  117. return (T)CreateInstance(typeof(T), additionalObjects);
  118. }
  119. public object CreateInstance(Type typeToInstantiate, params object[] additionalParameter)
  120. {
  121. AssertContainerIsNotDisposed();
  122. object result = TryCreate(typeToInstantiate, additionalParameter);
  123. if (result == null)
  124. throw new ServiceContainerException(typeToInstantiate, "Could not create object");
  125. return result;
  126. }
  127. public T CreateInstance<T>(string serviceId, params object[] additionalObjects) where T : class
  128. {
  129. return (T)CreateInstance(typeof(T),serviceId, additionalObjects);
  130. }
  131. public object CreateInstance(Type typeToInstantiate,string serviceId, params object[] additionalParameter)
  132. {
  133. AssertContainerIsNotDisposed();
  134. object result = TryCreate(typeToInstantiate, serviceId, additionalParameter);
  135. if (result == null)
  136. throw new ServiceContainerException(typeToInstantiate, "Could not create object");
  137. return result;
  138. }
  139. private void AssertContainerIsNotDisposed()
  140. {
  141. if (isDisposed)
  142. throw new ObjectDisposedException(GetType().Name);
  143. }
  144. public object TryGetService(Type serviceType)
  145. {
  146. return TryGetService(serviceType, string.Empty);
  147. }
  148. public object TryGetService(Type serviceType, string serviceId)
  149. {
  150. object service;
  151. if (serviceType == typeof(IServiceLocator) || serviceType == typeof(IServiceContainer))
  152. return this;
  153. if (!services.TryGetValue(new ServiceKey(serviceType, serviceId), out service))
  154. {
  155. if (parentServiceLocator != null)
  156. return parentServiceLocator.TryGetService(serviceType, serviceId);
  157. return null;
  158. }
  159. return service;
  160. }
  161. public T TryGetService<T>()
  162. {
  163. return TryGetService<T>(string.Empty);
  164. }
  165. public T TryGetService<T>(string serviceId)
  166. {
  167. Type serviceType = typeof(T);
  168. object result;
  169. if (serviceType == typeof(IServiceLocator) || serviceType == typeof(IServiceContainer))
  170. result = this;
  171. else
  172. {
  173. if (!services.TryGetValue(new ServiceKey(serviceType, serviceId), out result))
  174. {
  175. if (parentServiceLocator != null)
  176. result = parentServiceLocator.TryGetService(serviceType, serviceId);
  177. }
  178. }
  179. return (T)result;
  180. }
  181. private object TryCreate(Type typeToCreate, params object[] additionalObjects)
  182. {
  183. return TryCreate(typeToCreate, string.Empty, additionalObjects);
  184. }
  185. private object TryCreate(Type typeToCreate, string serviceId, params object[] additionalObjects)
  186. {
  187. var constructors = typeToCreate.GetConstructors();
  188. Array.Reverse(constructors);
  189. List<object> parameters = new List<object>();
  190. ConstructorInfo foundConstructor = null;
  191. foreach (ConstructorInfo constructor in constructors)
  192. {
  193. var parameterInfos = constructor.GetParameters();
  194. parameters.Clear();
  195. foreach (var parameterInfo in parameterInfos)
  196. {
  197. var dependency = TryGetService(parameterInfo.ParameterType, serviceId);
  198. if (dependency != null)
  199. {
  200. parameters.Add(dependency);
  201. }
  202. else
  203. {
  204. int firstMatchingParameterObjectIndex = -1;
  205. for (int index = 0; index < additionalObjects.Length; index++)
  206. {
  207. object additionalObject = additionalObjects[index];
  208. if (parameterInfo.ParameterType.IsAssignableFrom(additionalObject.GetType()))
  209. {
  210. firstMatchingParameterObjectIndex = index;
  211. break;
  212. }
  213. }
  214. if (firstMatchingParameterObjectIndex >= 0)
  215. {
  216. parameters.Add(additionalObjects[firstMatchingParameterObjectIndex]);
  217. }
  218. }
  219. }
  220. if (parameters.Count == parameterInfos.Length)
  221. {
  222. foundConstructor = constructor;
  223. break;
  224. }
  225. }
  226. if (foundConstructor != null)
  227. {
  228. var stateObject = foundConstructor.Invoke(parameters.ToArray());
  229. return stateObject;
  230. }
  231. return null;
  232. }
  233. // Help struct used as key in the dictionary of the container
  234. private struct ServiceKey
  235. {
  236. private readonly Type _typeOfObject;
  237. private readonly string _id;
  238. public ServiceKey(Type typeOfObject, string id)
  239. {
  240. _typeOfObject = typeOfObject;
  241. _id = id;
  242. }
  243. public ServiceKey(Type typeOfObject)
  244. {
  245. _typeOfObject = typeOfObject;
  246. _id = string.Empty;
  247. }
  248. public override int GetHashCode()
  249. {
  250. int hash = 17;
  251. hash = hash*31 + _typeOfObject.GetHashCode();
  252. hash = hash * 31 + _id.GetHashCode();
  253. return hash;
  254. }
  255. public override bool Equals(object obj)
  256. {
  257. return obj is ServiceKey && this == (ServiceKey)obj;
  258. }
  259. public static bool operator ==(ServiceKey s1, ServiceKey s2)
  260. {
  261. return (s1._typeOfObject == s2._typeOfObject) && (s1._id.Equals(s2._id, StringComparison.InvariantCulture));
  262. }
  263. public static bool operator !=(ServiceKey s1, ServiceKey s2)
  264. {
  265. return !(s1 == s2);
  266. }
  267. }
  268. #region Implementation of IDisposable
  269. ~ServiceContainer()
  270. {
  271. Dispose(false);
  272. }
  273. public void Dispose()
  274. {
  275. Dispose(true);
  276. GC.SuppressFinalize(this);
  277. }
  278. private void Dispose(bool disposing)
  279. {
  280. if (disposing)
  281. {
  282. isDisposed = true;
  283. foreach (var service in services.Values)
  284. {
  285. var disposable = service as IDisposable;
  286. if (disposable != null)
  287. {
  288. try
  289. {
  290. disposable.Dispose();
  291. }
  292. catch
  293. {
  294. //Ignore errors
  295. }
  296. }
  297. }
  298. }
  299. }
  300. #endregion
  301. }
  302. }