BaseApplicationHost.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. using MediaBrowser.Common.Implementations.Udp;
  2. using MediaBrowser.Common.Implementations.Updates;
  3. using MediaBrowser.Common.Implementations.WebSocket;
  4. using MediaBrowser.Common.Kernel;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Common.ScheduledTasks;
  7. using MediaBrowser.Common.Updates;
  8. using MediaBrowser.Model.Logging;
  9. using MediaBrowser.Model.Serialization;
  10. using SimpleInjector;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Reflection;
  16. using System.Threading;
  17. namespace MediaBrowser.Common.Implementations
  18. {
  19. public abstract class BaseApplicationHost
  20. {
  21. /// <summary>
  22. /// Gets or sets the logger.
  23. /// </summary>
  24. /// <value>The logger.</value>
  25. public ILogger Logger { get; protected set; }
  26. /// <summary>
  27. /// Gets or sets the log manager.
  28. /// </summary>
  29. /// <value>The log manager.</value>
  30. public ILogManager LogManager { get; protected set; }
  31. /// <summary>
  32. /// Gets the application paths.
  33. /// </summary>
  34. /// <value>The application paths.</value>
  35. protected IApplicationPaths ApplicationPaths { get; private set; }
  36. /// <summary>
  37. /// The container
  38. /// </summary>
  39. protected readonly Container Container = new Container();
  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. /// Finds the parts.
  122. /// </summary>
  123. protected virtual void FindParts()
  124. {
  125. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  126. Resolve<IHttpServer>().Init(GetExports<IRestfulService>(false));
  127. Resolve<IServerManager>().AddWebSocketListeners(GetExports<IWebSocketListener>());
  128. }
  129. /// <summary>
  130. /// Discovers the types.
  131. /// </summary>
  132. protected void DiscoverTypes()
  133. {
  134. FailedAssemblies.Clear();
  135. AllTypes = GetComposablePartAssemblies().SelectMany(GetTypes).ToArray();
  136. AllConcreteTypes = AllTypes.Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType).ToArray();
  137. }
  138. /// <summary>
  139. /// Registers resources that classes will depend on
  140. /// </summary>
  141. protected virtual void RegisterResources(ITaskManager taskManager, INetworkManager networkManager, IServerManager serverManager)
  142. {
  143. RegisterSingleInstance(LogManager);
  144. RegisterSingleInstance(Logger);
  145. RegisterSingleInstance(ApplicationPaths);
  146. RegisterSingleInstance(taskManager);
  147. RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
  148. RegisterSingleInstance(ProtobufSerializer);
  149. RegisterSingleInstance<IUdpServer>(new UdpServer(Logger), false);
  150. RegisterSingleInstance<IPackageManager>(new PackageManager());
  151. RegisterSingleInstance(networkManager);
  152. RegisterSingleInstance(serverManager);
  153. }
  154. /// <summary>
  155. /// Gets a list of types within an assembly
  156. /// 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
  157. /// </summary>
  158. /// <param name="assembly">The assembly.</param>
  159. /// <returns>IEnumerable{Type}.</returns>
  160. /// <exception cref="System.ArgumentNullException">assembly</exception>
  161. protected IEnumerable<Type> GetTypes(Assembly assembly)
  162. {
  163. if (assembly == null)
  164. {
  165. throw new ArgumentNullException("assembly");
  166. }
  167. try
  168. {
  169. return assembly.GetTypes();
  170. }
  171. catch (ReflectionTypeLoadException ex)
  172. {
  173. // If it fails we can still get a list of the Types it was able to resolve
  174. return ex.Types.Where(t => t != null);
  175. }
  176. }
  177. /// <summary>
  178. /// Creates an instance of type and resolves all constructor dependancies
  179. /// </summary>
  180. /// <param name="type">The type.</param>
  181. /// <returns>System.Object.</returns>
  182. public object CreateInstance(Type type)
  183. {
  184. try
  185. {
  186. return Container.GetInstance(type);
  187. }
  188. catch
  189. {
  190. Logger.Error("Error creating {0}", type.Name);
  191. throw;
  192. }
  193. }
  194. /// <summary>
  195. /// Registers the specified obj.
  196. /// </summary>
  197. /// <typeparam name="T"></typeparam>
  198. /// <param name="obj">The obj.</param>
  199. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  200. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  201. where T : class
  202. {
  203. Container.RegisterSingle(obj);
  204. if (manageLifetime)
  205. {
  206. var disposable = obj as IDisposable;
  207. if (disposable != null)
  208. {
  209. Logger.Info("Registering " + disposable.GetType().Name);
  210. DisposableParts.Add(disposable);
  211. }
  212. }
  213. }
  214. /// <summary>
  215. /// Registers the single instance.
  216. /// </summary>
  217. /// <typeparam name="T"></typeparam>
  218. /// <param name="func">The func.</param>
  219. protected void RegisterSingleInstance<T>(Func<T> func)
  220. where T : class
  221. {
  222. Container.RegisterSingle(func);
  223. }
  224. /// <summary>
  225. /// Resolves this instance.
  226. /// </summary>
  227. /// <typeparam name="T"></typeparam>
  228. /// <returns>``0.</returns>
  229. public T Resolve<T>()
  230. {
  231. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  232. }
  233. /// <summary>
  234. /// Resolves this instance.
  235. /// </summary>
  236. /// <typeparam name="T"></typeparam>
  237. /// <returns>``0.</returns>
  238. public T TryResolve<T>()
  239. {
  240. var result = Container.GetRegistration(typeof(T), false);
  241. if (result == null)
  242. {
  243. return default(T);
  244. }
  245. return (T)result.GetInstance();
  246. }
  247. /// <summary>
  248. /// Loads the assembly.
  249. /// </summary>
  250. /// <param name="file">The file.</param>
  251. /// <returns>Assembly.</returns>
  252. protected Assembly LoadAssembly(string file)
  253. {
  254. try
  255. {
  256. return Assembly.Load(File.ReadAllBytes((file)));
  257. }
  258. catch (Exception ex)
  259. {
  260. FailedAssemblies.Add(file);
  261. Logger.ErrorException("Error loading assembly {0}", ex, file);
  262. return null;
  263. }
  264. }
  265. /// <summary>
  266. /// Gets the exports.
  267. /// </summary>
  268. /// <typeparam name="T"></typeparam>
  269. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  270. /// <returns>IEnumerable{``0}.</returns>
  271. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  272. {
  273. var currentType = typeof(T);
  274. Logger.Info("Composing instances of " + currentType.Name);
  275. var parts = AllConcreteTypes.Where(currentType.IsAssignableFrom).Select(CreateInstance).Cast<T>().ToArray();
  276. if (manageLiftime)
  277. {
  278. DisposableParts.AddRange(parts.OfType<IDisposable>());
  279. }
  280. return parts;
  281. }
  282. /// <summary>
  283. /// Gets the current application version
  284. /// </summary>
  285. /// <value>The application version.</value>
  286. public Version ApplicationVersion
  287. {
  288. get
  289. {
  290. return GetType().Assembly.GetName().Version;
  291. }
  292. }
  293. /// <summary>
  294. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  295. /// </summary>
  296. public void Dispose()
  297. {
  298. Dispose(true);
  299. }
  300. /// <summary>
  301. /// Releases unmanaged and - optionally - managed resources.
  302. /// </summary>
  303. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  304. protected virtual void Dispose(bool dispose)
  305. {
  306. if (dispose)
  307. {
  308. var type = GetType();
  309. Logger.Info("Disposing " + type.Name);
  310. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  311. DisposableParts.Clear();
  312. foreach (var part in parts)
  313. {
  314. Logger.Info("Disposing " + part.GetType().Name);
  315. part.Dispose();
  316. }
  317. }
  318. }
  319. }
  320. }