【问题标题】:Creating a base class for Windows Services为 Windows 服务创建基类
【发布时间】:2012-02-11 12:56:19
【问题描述】:

在我们的应用程序中,我们有许多 Windows 服务(超过 30 个)必须在后台运行,以便在一天中的给定时间处理数据。我试图创建一个可以继承的 BaseService 类,当服务启动或停止以及其他一些常见功能时,它会记录到我们的数据库中。但是,我在尝试将 BaseService 创建为 MustInherit 时遇到了麻烦,因为我们有许多 MustOverride 属性。问题在于:

<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。这就是我的问题。我不能在基类中创建它,也不能在继承类中覆盖它。

【问题讨论】:

  • Main 是应用程序的一种方法,而不是服务的方法,因为一个应用程序可以托管多个服务。您可以将应用程序和服务分成不同的类,这可能会使您的任务更轻松。

标签: vb.net windows-services base-class


【解决方案1】:

以下是我们解决这个确切问题的方法:我们将实现类型传递给基础服务类中的共享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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    相关资源
    最近更新 更多