files

Code Snippets

Title: WCF Proxy Helper Class
Description: Class to help initiate, action and close the service
Category: WCF
Visibility:  Public
Added by: db7uk on 5/6/2012

 Currently rated 5 by 3 user(s)

Get link for this code snippet
Collapse code snippet
Expand code snippet
Tweet this snippet
Tweet about this snippet
Delete code snippet
Edit code snippet
Imports System.ServiceModel

Namespace WCF
    ''' <summary>
    ''' Service helper class to instanciate, open, action and close a service method(s)
    ''' </summary>
    ''' <remarks></remarks>
    Public Class ServiceHelper
        ''' <summary>
        ''' WCF proxys do not clean up properly if they throw an exception. This method ensures that the service proxy is handeled correctly.
        ''' Do not call TService.Close() or TService.Abort() within the action lambda.
        ''' </summary>
        ''' <typeparam name="TService">The type of the service to use</typeparam>
        ''' <param name="action">Lambda of the action to performwith the service</param>
        Public Shared Sub [Using](Of TService As {ICommunicationObject, IDisposable, New})(action As Action(Of TService))
            Dim service = New TService()
            Try
                action(service)
            Finally
                Close(service)
            End Try
        End Sub

        ''' <summary>
        ''' Closes the service.
        ''' </summary>
        ''' <param name="service">The service.</param>
        ''' <remarks></remarks>
        Public Shared Sub Close(service As ICommunicationObject)
            Dim success As Boolean = False
            Try
                If service.State <> (CommunicationState.Faulted) Then
                    service.Close()
                    success = True
                End If
            Finally
                If Not success Then
                    service.Abort()
                End If
            End Try
        End Sub
    End Class
End Namespace