2010-06-24 127 views
1

我想創建一個窗口服務,可以從某個位置加載多個DLL並使用特定的TCP端口上的遠程處理(例如9000)發佈它們。C#Windows服務和遠程處理

每個DLL包含一個將發佈的類。

例如(Test.dll的)

namespace Test 
{ 
    class Service 
    { 
    // methods here 
    } 
} 

服務應該使用Remoting的tcp://<servername>:9000/Test.dll

我知道如何使用遠程處理,但我想知道如何實現服務,以便發佈它可以在啓動時動態加載DLL,並在停止時卸載它們。

可能還有其他方法可以做到這一點嗎?

回答

0

如果您正在尋找可靠的解決方案,請查看MEF,託管擴展性框架。

但是,如果你只是要加載的DLL文件一樣簡單的插件,我有一些代碼樣本,我TournamentApi

/// <summary> 
/// Provides methods to load plugins from external assemblies. 
/// </summary> 
public static class PluginLoader 
{ 
    ... 

    /// <summary> 
    /// Loads the plugins from a specified assembly. 
    /// </summary> 
    /// <param name="assembly">The assembly from which to load.</param> 
    /// <returns>The plugin factories contained in the assembly, if the load was successful; null, otherwise.</returns> 
    public static IEnumerable<IPluginFactory> LoadPlugins(Assembly assembly) 
    { 
     var factories = new List<IPluginFactory>(); 

     try 
     { 
      foreach (var type in assembly.GetTypes()) 
      { 
       IPluginEnumerator instance = null; 

       if (type.GetInterface("IPluginEnumerator") != null) 
       { 
        instance = (IPluginEnumerator)Activator.CreateInstance(type); 
       } 

       if (instance != null) 
       { 
        factories.AddRange(instance.EnumerateFactories()); 
       } 
      } 
     } 
     catch (SecurityException ex) 
     { 
      throw new LoadPluginsFailureException("Loading of plugins failed. Check the inner exception for more details.", ex); 
     } 
     catch (ReflectionTypeLoadException ex) 
     { 
      throw new LoadPluginsFailureException("Loading of plugins failed. Check the inner exception for more details.", ex); 
     } 

     return factories.AsReadOnly(); 
    } 
} 

這需要加載的程序集和實例每個IPluginEnumerator的實例在裝配並且它會返回它支持的每個IPluginFactory(Abstract Factory)。

請隨時查看其他代碼的TournamentApi項目的源代碼。