访问WCF服务的单个实例

时间:2018-05-14 09:10:05

标签: vb.net wcf

我在VB.NET中创建了我的第一个WCF服务,它由外部IIS服务器托管。我想从我的主应用程序中的不同点访问此服务。主应用程序由不同的用户使用,并在多台计算机上运行。

mainapplication的实例应使用WCF服务来共享数据。例如,List(Of T)在某个点创建,并在另一个点或主应用程序的另一个实例中使用。我想在外部IIS上只运行一个服务的单个实例,由多个用户(应用程序/计算机)使用。

这就是我所做的。我创建了一个名为IemmbeeService的接口(ServiceContract)。为简单起见,下面的示例仅包含一种方法:

Imports System.ServiceModel

<ServiceContract()>
Public Interface IemmbeeService

    <OperationContract>
    Function GetServiceId() As Guid
End Interface

这是实施:

Public Class emmbeeService
Implements IemmbeeService

    Private _serviceId As Guid

    Public Sub New()
        _serviceId = Guid.NewGuid
    End Sub

    Public Function GetServiceId() As Guid Implements IemmbeeService.GetServiceId
        Return _serviceId
    End Function
End Class

如您所见,方法GetServiceId返回一个Guid,它只在构造函数中创建一次。

这是我在主应用程序中创建服务实例的方法:

Public Function GetemmbeeService(endpoint As String) As IemmbeeService
        Dim es As IemmbeeService = New emmbeeService
        es = ChannelFactory(Of IemmbeeService).CreateChannel(New BasicHttpBinding(), New EndpointAddress(New Uri(endpoint)))
        Return es
End Function

使用服务的示例:

Dim endpoint As String = ""http://myServer/emmbeeFramework/emmbeeService.svc"
emmbeeService = GetemmbeeService(endpoint)
Dim abc As Guid = emmbeeService.GetServiceId

这很有效。我能够访问该服务并使用其所有方法。但后来我想创建一个List(of T)用于共享目的。将项添加到列表中可以正常工作,但是当我想在应用程序的另一个点访问此列表时,列表不会产生任何结果。

然后我尝试了以下内容:

Dim endpoint As String = ""http://myServer/emmbeeFramework/emmbeeService.svc"
emmbeeService = GetemmbeeService(endpoint)
Dim abc As Guid = emmbeeService.GetServiceId
Dim def As Guid = emmbeeService.GetServiceId
Dim ghi As Guid = emmbeeService.GetServiceId

我希望将相同的ServiceId重新接收三次(因为我只访问该服务的一个单一实例,而ServiceId只在服务的构造函数中创建一次) - 而是服务返回三个不同的guid

我的错误是什么?或者我是否完全误解了WCF服务?

1 个答案:

答案 0 :(得分:0)

使用InstanceContextMode是解决方案:

<ServiceBehavior(InstanceContextMode:=InstanceContextMode.Single)>
Public Class emmbeeService
    Implements IemmbeeService

    ...
End Class