BaseApplicationHost.cs 11 KB

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