ExportFactory.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using SuperSocket.Common;
  6. namespace SuperSocket.SocketBase.Provider
  7. {
  8. /// <summary>
  9. /// Export Factory
  10. /// </summary>
  11. [Serializable]
  12. public class ExportFactory
  13. {
  14. /// <summary>
  15. /// Gets or sets the type.
  16. /// </summary>
  17. /// <value>
  18. /// The type.
  19. /// </value>
  20. public string TypeName { get; set; }
  21. private Type m_LoadedType;
  22. [NonSerialized]
  23. private object m_Instance;
  24. /// <summary>
  25. /// Initializes a new instance of the <see cref="ExportFactory"/> class.
  26. /// </summary>
  27. public ExportFactory()
  28. {
  29. }
  30. /// <summary>
  31. /// Initializes a new instance of the <see cref="ExportFactory"/> class.
  32. /// </summary>
  33. /// <param name="instance">The instance.</param>
  34. public ExportFactory(object instance)
  35. {
  36. m_Instance = instance;
  37. }
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="ExportFactory"/> class.
  40. /// </summary>
  41. /// <param name="typeName">Name of the type.</param>
  42. public ExportFactory(string typeName)
  43. {
  44. TypeName = typeName;
  45. }
  46. /// <summary>
  47. /// Ensures the instance's existance.
  48. /// </summary>
  49. public void EnsureInstance()
  50. {
  51. if (m_Instance != null)
  52. return;
  53. m_Instance = CreateInstance();
  54. }
  55. private object CreateInstance()
  56. {
  57. if (m_LoadedType == null)
  58. {
  59. m_LoadedType = AssemblyUtil.GetType(TypeName, true, true);
  60. }
  61. return Activator.CreateInstance(m_LoadedType);
  62. }
  63. /// <summary>
  64. /// Creates the export type instance.
  65. /// </summary>
  66. /// <typeparam name="T"></typeparam>
  67. /// <returns></returns>
  68. public T CreateExport<T>()
  69. {
  70. if (m_Instance != null)
  71. return (T)m_Instance;
  72. return (T)CreateInstance();
  73. }
  74. /// <summary>
  75. /// Creates the export type instance from the instance creator.
  76. /// </summary>
  77. /// <typeparam name="T"></typeparam>
  78. /// <param name="creator">The creator.</param>
  79. /// <returns></returns>
  80. public T CreateExport<T>(Func<Type, object> creator)
  81. {
  82. if (m_LoadedType == null)
  83. {
  84. m_LoadedType = AssemblyUtil.GetType(TypeName, true, true);
  85. }
  86. return (T)creator(m_LoadedType);
  87. }
  88. }
  89. }