2012-01-16 41 views
0

在我們的應用程序中,我們有許多Windows服務(超過30個),必須在幕後運行以在一天中的特定時間處理數據。我試圖創建一個BaseService類,我可以繼承該類,該類將在服務啓動或停止時以及其他一些常用功能登錄到我們的數據庫。然而,我試圖將BaseService創建爲MustInherit,因爲我們有一些MustOverride屬性。問題在於:爲Windows服務創建基類

<MTAThread()> Shared Sub Main() 

我們的代碼都是在VB中(你可能會說)。鑑於它是一個共享方法,我不能重寫它(即使它成爲MustOverride)。如果沒有這種方法,代碼將無法編譯,但它不會真正在基類中工作。此方法中的代碼是:

Dim ServicesToRun() As System.ServiceProcess.ServiceBase 
ServicesToRun = New System.ServiceProcess.ServiceBase() {New BaseService} 
System.ServiceProcess.ServiceBase.Run(ServicesToRun) 

無法創建BaseService(我的基類的名稱),因爲它被指定爲MustInherit。其中存在我的問題。我不能在基類中創建它,並且無法在繼承類中重寫它。

+0

主要是一個應用程序的方法,而不是一種服務,因爲一個應用程序可以承載多個服務您可以將應用程序和服務分爲不同的類,這可能會使您的任務更輕鬆。 – 2012-01-16 15:57:48

回答

0

下面是我們如何解決這個確切的問題:我們將實現類型傳遞給基類服務類中的共享MainBase,然後從實現類調用此類。

下面是從基本服務類的代碼:

' The main entry point for the process 
<MTAThread()> _ 
Shared Sub MainBase(ByVal ImplementingType As System.Type) 
    Dim ServicesToRun() As System.ServiceProcess.ServiceBase 

    If InStr(Environment.CommandLine, "StartAsProcess", CompareMethod.Text) <> 0 Then 
     DirectCast(Activator.CreateInstance(ImplementingType), ServerMonitorServiceBase).OnStart(Nothing) 
    Else 
     ServicesToRun = New System.ServiceProcess.ServiceBase() {DirectCast(Activator.CreateInstance(ImplementingType), ServiceBase)} 
     System.ServiceProcess.ServiceBase.Run(ServicesToRun) 
    End If 

End Sub 

這裏是從實現類的代碼:

' The main entry point for the process. The main method can't be inherited, so 
' implement this workaround 
<MTAThread(), LoaderOptimization(LoaderOptimization.MultiDomain)> _ 
Shared Sub Main() 

    Call MainBase(GetType(ThisImplementedService)) 
End Sub 
+0

謝謝。這看起來會起作用。 – GreenEggsAndHam 2012-01-16 18:09:07