2009-11-06 35 views
0

我們正試圖在同一進程下實現一個啓動多個服務的Windows服務。根據代碼我看到你做以下事情:同一進程下的多個Windows服務未啓動

static void Main() 
    { 
     ServiceBase[] ServicesToRun; 
     ServicesToRun = new ServiceBase[] 
     { 
      new Service1(), 
      new Service2() 
     }; 
     ServiceBase.Run(ServicesToRun); 
    } 

但是,此代碼只執行Service1而不是Service2。 Service1和Service2自行執行。有任何想法嗎?

+0

您是否在尋找兩個獨立的物理Windows服務或一個執行兩個功能的Windows服務? – zac 2009-11-06 00:24:00

+0

您的Service1/Service2的外觀如何?他們得到了OnStart方法和不同的ServiceName? – 2009-11-06 01:14:55

+0

@Anders是的。事實上,兩人都將開始並單獨運行。 – 2009-11-06 16:24:42

回答

3

我想你會想創建一個子服務模型,其中可以從主窗口服務啓動任意數量的子服務。

那麼也許基螺紋服務類..

public abstract class ThreadedService : ISubService 
{ 
    private Thread m_thread; 

    private ThreadedService() 
    { 
     m_thread = new Thread(new ThreadStart(StartThread)); 
    } 

    // implement the interface 
} 

通過的app.config和IConfigurationSectionHandler配置您的服務...

public class ServiceConfigurationHandler : IConfigurationSectionHandler 
{ 
    public ServiceConfigurationHandler() { } 

    public object Create(object parent, object configContext, XmlNode section) 
    { 
     return new ServiceConfiguration((XmlElement)section); 
    } 
} 

東西來處理配置部分...

public class ServiceConfiguration 
{ 
    public static readonly ServiceConfiguration Current = (ServiceConfiguration)ConfigurationManager.GetSection("me/services"); 

    private List<ISubService> m_services; 
    private string m_serviceName; 

    internal ServiceConfiguration(XmlElement xmlSection) 
    { 
     // loop through the config and initialize the services 
     // service = createinstance(type)..kind of deal 
     // m_services.Add(service); 
    } 

    public void Start() 
    { 
     foreach(ISubService service in m_services) { service.Start(); }   
    } 
    public void Stop() { ... } 
} 

那麼你只需創建你需要爲你的子服務,但是許多基於threadedservice類,它們都扔到的app.config ...像..

<me> 
    <services> 
    <service type="my.library.service1,my.library" /> 
    <service type="my.library.service2,my.library" /> 
    </services> 
</me> 

,最後,在實際的服務代碼,只需要在啓動時執行ServiceConfiguration.Current.Start(),並在出口執行Service.Configuration.Current.Stop()。

希望有幫助!

+0

這是一個有趣的想法。這是否允許我們獨立地編譯新庫並將它們添加到服務中,而不必通過將服務添加到app.config來重新編譯服務?這將是一個非常可擴展的解決方案! – 2009-11-06 16:33:26

+0

是的,這完全是這個解決方案的意圖。我們不斷添加迷你服務,並且不想接觸Windows服務處理程序。在應用配置中放置一條新線,而且你很棒。 – Sean 2009-11-09 21:12:54