在我们的应用程序中,我们有许多Windows服务(超过30个)必须在幕后运行,以便在一天中的给定时间处理数据。我试图创建一个我可以继承的BaseService类,它将在服务启动或停止时登录到我们的数据库以及其他一些常用功能。但是,由于我们有许多MustOverride属性,因此尝试创建BaseService作为MustInherit时遇到了一个显示停止。问题在于:
<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。这就是我的问题所在。我不能在Base Class中创建它,也不能在继承类中覆盖它。
答案 0 :(得分: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