LEANWORK.NET

Lean Solutions & Rich User Experiences

WCF Helpers

[Updated June 1, 2015]

Makes using WCF channels easier

  • Gets WCF client config from .config file.
  • Caches ChannelFactories.
  • Robustly closes channels.
Download code.

Code

Public Class CachedChannelFactory

  Private Shared _channelFactoryCache
      As New ConcurrentDictionary(Of String, ChannelFactory)

  Public Shared Function CreateChannel(Of T)() As T

    Dim fac As ChannelFactory(Of T) =
         _channelFactoryCache.GetOrAdd(
                          GetType(T).ToString,
                         
New ChannelFactory(Of T)(""))
    Return fac.CreateChannel()
  
End Function

   'Fix for WCF proxy dispose() throwing on faulted channel
  
Public Shared Sub CloseChannel(channel As IClientChannel)

      If channel Is Nothing Then Return

      Try
         
channel.Close()
     
Catch __ As CommunicationException
         
channel.Abort()
     
Catch __ As TimeoutException
         
channel.Abort()
     
Catch __ As Exception
          
channel.Abort()
         
Throw
     
End Try

  End Sub
End Class

Usage

Dim svc As IWCFService1 =
      CachedChannelFactory.CreateChannel(Of IWCFService1)()

Try
   
Dim echo = svc.Echo(TextBox1.Text)
   
ListBox1.Items.Add(echo) 

Catch ex As Exception
   
MessageBox.Show(ex.Message)
Finally
   
CachedChannelFactory.CloseChannel(svc)

End Try