2012-01-16 48 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