BaseApplicationHost.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. using System.IO;
  2. using System.Linq;
  3. using System.Reflection;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Serialization;
  6. using SimpleInjector;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Threading;
  10. namespace MediaBrowser.Common.Implementations
  11. {
  12. public abstract class BaseApplicationHost : IDisposable
  13. {
  14. /// <summary>
  15. /// Gets or sets the logger.
  16. /// </summary>
  17. /// <value>The logger.</value>
  18. public ILogger Logger { get; protected set; }
  19. /// <summary>
  20. /// The container
  21. /// </summary>
  22. protected readonly Container Container = new Container();
  23. /// <summary>
  24. /// Gets assemblies that failed to load
  25. /// </summary>
  26. public List<string> FailedAssemblies { get; protected set; }
  27. /// <summary>
  28. /// Gets all types within all running assemblies
  29. /// </summary>
  30. /// <value>All types.</value>
  31. public Type[] AllTypes { get; protected set; }
  32. /// <summary>
  33. /// Gets all concrete types.
  34. /// </summary>
  35. /// <value>All concrete types.</value>
  36. public Type[] AllConcreteTypes { get; protected set; }
  37. /// <summary>
  38. /// The disposable parts
  39. /// </summary>
  40. protected readonly List<IDisposable> DisposableParts = new List<IDisposable>();
  41. /// <summary>
  42. /// The _protobuf serializer initialized
  43. /// </summary>
  44. private bool _protobufSerializerInitialized;
  45. /// <summary>
  46. /// The _protobuf serializer sync lock
  47. /// </summary>
  48. private object _protobufSerializerSyncLock = new object();
  49. /// <summary>
  50. /// Gets a dynamically compiled generated serializer that can serialize protocontracts without reflection
  51. /// </summary>
  52. private IProtobufSerializer _protobufSerializer;
  53. /// <summary>
  54. /// Gets the protobuf serializer.
  55. /// </summary>
  56. /// <value>The protobuf serializer.</value>
  57. protected IProtobufSerializer ProtobufSerializer
  58. {
  59. get
  60. {
  61. // Lazy load
  62. LazyInitializer.EnsureInitialized(ref _protobufSerializer, ref _protobufSerializerInitialized, ref _protobufSerializerSyncLock, () => Serialization.ProtobufSerializer.Create(AllTypes));
  63. return _protobufSerializer;
  64. }
  65. private set
  66. {
  67. _protobufSerializer = value;
  68. _protobufSerializerInitialized = value != null;
  69. }
  70. }
  71. /// <summary>
  72. /// Initializes a new instance of the <see cref="BaseApplicationHost" /> class.
  73. /// </summary>
  74. protected BaseApplicationHost()
  75. {
  76. FailedAssemblies = new List<string>();
  77. }
  78. /// <summary>
  79. /// Gets the composable part assemblies.
  80. /// </summary>
  81. /// <returns>IEnumerable{Assembly}.</returns>
  82. protected abstract IEnumerable<Assembly> GetComposablePartAssemblies();
  83. /// <summary>
  84. /// Discovers the types.
  85. /// </summary>
  86. protected void DiscoverTypes()
  87. {
  88. FailedAssemblies.Clear();
  89. AllTypes = GetComposablePartAssemblies().SelectMany(GetTypes).ToArray();
  90. AllConcreteTypes = AllTypes.Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType).ToArray();
  91. }
  92. /// <summary>
  93. /// Gets a list of types within an assembly
  94. /// This will handle situations that would normally throw an exception - such as a type within the assembly that depends on some other non-existant reference
  95. /// </summary>
  96. /// <param name="assembly">The assembly.</param>
  97. /// <returns>IEnumerable{Type}.</returns>
  98. /// <exception cref="System.ArgumentNullException">assembly</exception>
  99. protected IEnumerable<Type> GetTypes(Assembly assembly)
  100. {
  101. if (assembly == null)
  102. {
  103. throw new ArgumentNullException("assembly");
  104. }
  105. try
  106. {
  107. return assembly.GetTypes();
  108. }
  109. catch (ReflectionTypeLoadException ex)
  110. {
  111. // If it fails we can still get a list of the Types it was able to resolve
  112. return ex.Types.Where(t => t != null);
  113. }
  114. }
  115. /// <summary>
  116. /// Creates an instance of type and resolves all constructor dependancies
  117. /// </summary>
  118. /// <param name="type">The type.</param>
  119. /// <returns>System.Object.</returns>
  120. public object CreateInstance(Type type)
  121. {
  122. try
  123. {
  124. return Container.GetInstance(type);
  125. }
  126. catch
  127. {
  128. Logger.Error("Error creating {0}", type.Name);
  129. throw;
  130. }
  131. }
  132. /// <summary>
  133. /// Registers the specified obj.
  134. /// </summary>
  135. /// <typeparam name="T"></typeparam>
  136. /// <param name="obj">The obj.</param>
  137. protected void RegisterSingleInstance<T>(T obj)
  138. where T : class
  139. {
  140. Container.RegisterSingle(obj);
  141. }
  142. /// <summary>
  143. /// Registers the specified func.
  144. /// </summary>
  145. /// <typeparam name="T"></typeparam>
  146. /// <param name="func">The func.</param>
  147. protected void Register<T>(Func<T> func)
  148. where T : class
  149. {
  150. Container.Register(func);
  151. }
  152. /// <summary>
  153. /// Registers the single instance.
  154. /// </summary>
  155. /// <typeparam name="T"></typeparam>
  156. /// <param name="func">The func.</param>
  157. protected void RegisterSingleInstance<T>(Func<T> func)
  158. where T : class
  159. {
  160. Container.RegisterSingle(func);
  161. }
  162. /// <summary>
  163. /// Resolves this instance.
  164. /// </summary>
  165. /// <typeparam name="T"></typeparam>
  166. /// <returns>``0.</returns>
  167. public T Resolve<T>()
  168. {
  169. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  170. }
  171. /// <summary>
  172. /// Resolves this instance.
  173. /// </summary>
  174. /// <typeparam name="T"></typeparam>
  175. /// <returns>``0.</returns>
  176. public T TryResolve<T>()
  177. {
  178. var result = Container.GetRegistration(typeof(T), false);
  179. if (result == null)
  180. {
  181. return default(T);
  182. }
  183. return (T)result.GetInstance();
  184. }
  185. /// <summary>
  186. /// Registers the specified service type.
  187. /// </summary>
  188. /// <param name="serviceType">Type of the service.</param>
  189. /// <param name="implementation">Type of the concrete.</param>
  190. protected void Register(Type serviceType, Type implementation)
  191. {
  192. Container.Register(serviceType, implementation);
  193. }
  194. /// <summary>
  195. /// Loads the assembly.
  196. /// </summary>
  197. /// <param name="file">The file.</param>
  198. /// <returns>Assembly.</returns>
  199. protected Assembly LoadAssembly(string file)
  200. {
  201. try
  202. {
  203. return Assembly.Load(File.ReadAllBytes((file)));
  204. }
  205. catch (Exception ex)
  206. {
  207. FailedAssemblies.Add(file);
  208. Logger.ErrorException("Error loading assembly {0}", ex, file);
  209. return null;
  210. }
  211. }
  212. /// <summary>
  213. /// Gets the exports.
  214. /// </summary>
  215. /// <typeparam name="T"></typeparam>
  216. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  217. /// <returns>IEnumerable{``0}.</returns>
  218. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  219. {
  220. var currentType = typeof(T);
  221. Logger.Info("Composing instances of " + currentType.Name);
  222. var parts = AllConcreteTypes.Where(currentType.IsAssignableFrom).Select(CreateInstance).Cast<T>().ToArray();
  223. if (manageLiftime)
  224. {
  225. DisposableParts.AddRange(parts.OfType<IDisposable>());
  226. }
  227. return parts;
  228. }
  229. /// <summary>
  230. /// Gets the current application version
  231. /// </summary>
  232. /// <value>The application version.</value>
  233. public Version ApplicationVersion
  234. {
  235. get
  236. {
  237. return GetType().Assembly.GetName().Version;
  238. }
  239. }
  240. /// <summary>
  241. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  242. /// </summary>
  243. public void Dispose()
  244. {
  245. Dispose(true);
  246. }
  247. /// <summary>
  248. /// Releases unmanaged and - optionally - managed resources.
  249. /// </summary>
  250. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  251. protected virtual void Dispose(bool dispose)
  252. {
  253. foreach (var part in DisposableParts)
  254. {
  255. part.Dispose();
  256. }
  257. var b = Container.GetCurrentRegistrations();
  258. DisposableParts.Clear();
  259. }
  260. }
  261. }