AppDomainAppServer.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.Reflection;
  3. using SuperSocket.SocketBase;
  4. using SuperSocket.SocketBase.Config;
  5. using SuperSocket.SocketBase.Provider;
  6. using System.IO;
  7. using SuperSocket.SocketBase.Metadata;
  8. namespace SuperSocket.SocketEngine
  9. {
  10. /// <summary>
  11. /// AppDomainAppServer
  12. /// </summary>
  13. partial class AppDomainAppServer : IsolationAppServer
  14. {
  15. private AppDomain m_HostDomain;
  16. /// <summary>
  17. /// Initializes a new instance of the <see cref="AppDomainAppServer" /> class.
  18. /// </summary>
  19. /// <param name="serverTypeName">Name of the server type.</param>
  20. /// <param name="serverStatusMetadata">The server status metadata.</param>
  21. public AppDomainAppServer(string serverTypeName, StatusInfoAttribute[] serverStatusMetadata)
  22. : base(serverTypeName, serverStatusMetadata)
  23. {
  24. }
  25. /// <summary>
  26. /// Starts this server instance.
  27. /// </summary>
  28. /// <returns>
  29. /// return true if start successfull, else false
  30. /// </returns>
  31. protected override IWorkItemBase Start()
  32. {
  33. IWorkItem appServer;
  34. try
  35. {
  36. m_HostDomain = CreateHostAppDomain();
  37. m_HostDomain.SetData(typeof(IsolationMode).Name, IsolationMode.AppDomain);
  38. var marshalServerType = typeof(MarshalAppServer);
  39. appServer = (IWorkItem)m_HostDomain.CreateInstanceAndUnwrap(marshalServerType.Assembly.FullName,
  40. marshalServerType.FullName,
  41. true,
  42. BindingFlags.CreateInstance,
  43. null,
  44. new object[] { ServerTypeName },
  45. null,
  46. new object[0]);
  47. if (!appServer.Setup(Bootstrap, Config, Factories))
  48. {
  49. OnExceptionThrown(new Exception("Failed to setup MarshalAppServer"));
  50. return null;
  51. }
  52. if (!appServer.Start())
  53. {
  54. OnExceptionThrown(new Exception("Failed to start MarshalAppServer"));
  55. return null;
  56. }
  57. m_HostDomain.DomainUnload += new EventHandler(m_HostDomain_DomainUnload);
  58. return appServer;
  59. }
  60. catch (Exception e)
  61. {
  62. if (m_HostDomain != null)
  63. {
  64. AppDomain.Unload(m_HostDomain);
  65. m_HostDomain = null;
  66. }
  67. OnExceptionThrown(e);
  68. return null;
  69. }
  70. }
  71. void m_HostDomain_DomainUnload(object sender, EventArgs e)
  72. {
  73. OnStopped();
  74. }
  75. protected override void OnStopped()
  76. {
  77. base.OnStopped();
  78. m_HostDomain = null;
  79. }
  80. protected override void Stop()
  81. {
  82. if (m_HostDomain != null)
  83. {
  84. AppDomain.Unload(m_HostDomain);
  85. }
  86. }
  87. }
  88. }