BaseApplicationHost.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  138. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  139. where T : class
  140. {
  141. Container.RegisterSingle(obj);
  142. if (manageLifetime)
  143. {
  144. var disposable = obj as IDisposable;
  145. if (disposable != null)
  146. {
  147. Logger.Info("Registering " + disposable.GetType().Name);
  148. DisposableParts.Add(disposable);
  149. }
  150. }
  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. /// Loads the assembly.
  187. /// </summary>
  188. /// <param name="file">The file.</param>
  189. /// <returns>Assembly.</returns>
  190. protected Assembly LoadAssembly(string file)
  191. {
  192. try
  193. {
  194. return Assembly.Load(File.ReadAllBytes((file)));
  195. }
  196. catch (Exception ex)
  197. {
  198. FailedAssemblies.Add(file);
  199. Logger.ErrorException("Error loading assembly {0}", ex, file);
  200. return null;
  201. }
  202. }
  203. /// <summary>
  204. /// Gets the exports.
  205. /// </summary>
  206. /// <typeparam name="T"></typeparam>
  207. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  208. /// <returns>IEnumerable{``0}.</returns>
  209. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  210. {
  211. var currentType = typeof(T);
  212. Logger.Info("Composing instances of " + currentType.Name);
  213. var parts = AllConcreteTypes.Where(currentType.IsAssignableFrom).Select(CreateInstance).Cast<T>().ToArray();
  214. if (manageLiftime)
  215. {
  216. DisposableParts.AddRange(parts.OfType<IDisposable>());
  217. }
  218. return parts;
  219. }
  220. /// <summary>
  221. /// Gets the current application version
  222. /// </summary>
  223. /// <value>The application version.</value>
  224. public Version ApplicationVersion
  225. {
  226. get
  227. {
  228. return GetType().Assembly.GetName().Version;
  229. }
  230. }
  231. /// <summary>
  232. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  233. /// </summary>
  234. public void Dispose()
  235. {
  236. Dispose(true);
  237. }
  238. /// <summary>
  239. /// Releases unmanaged and - optionally - managed resources.
  240. /// </summary>
  241. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  242. protected virtual void Dispose(bool dispose)
  243. {
  244. var type = GetType();
  245. Logger.Info("Disposing " + type.Name);
  246. foreach (var part in DisposableParts.Distinct().Where(i => i.GetType() != type).ToList())
  247. {
  248. Logger.Info("Disposing " + part.GetType().Name);
  249. part.Dispose();
  250. }
  251. DisposableParts.Clear();
  252. }
  253. }
  254. }