Thursday, June 17, 2010

Calling WCF service without AddReference

One of my Silverlight blog post is about creating a proxy without using the add reference menu in the Visual studio.The solution there is to write all the code which is auto generated when we add the reference through the proxy.ie we are just avoiding the auto generation and writing ourselves.Not a good solution.The reason we need to write all is because Silverlight supports only the Async service calls.But if we consider WPF we can call the service in Sync way.That means we can try out new things which will reduce our works in creating the manual proxy.

Didn’t get anything? In short we are going to create a proxy and call service without using the Add Service Reference menu or the any of the tool (eg:svcutil)available for generating the proxy.How can we achieve that.It’s simple .Share the contract dll.Important thing here is the sharing of contract dll is possible only because WPF and the WCF is using the same framework and runtime.This will not be possible in case of Silverlight since the runtime is different.

Ok.Lets start.We need 3 projects mainly.One is the Contracts where we keep all the WCF contracts.Then a service host project and a consumer of services.In the attached sample the host is a web host and the consumer is a WPF application.We can also host the WCF service in ConsoleHost.But in that case we need to solutions.Thats why I decided to go with WebHost.Below is solution structure.
Note that there is no ServiceReference in the WPF UI project.Only thing is the reference to Core project which contains all the contracts.App.Config should be same as of normal proxy creation in case you want to use default connection settings.All the magic happens inside the ServiceProxy class which is inheriting the ClientBase with a generic class.It will be clear after seeing the code below.
Imports System.ServiceModel
Imports ManualProxyTest.Core
Public Class ServiceProxy
    Inherits ClientBase(Of IMyService)
    Implements IMyService
    Public Function GetData(ByVal value As Integer) As String Implements IMyService.GetData
        Return Me.Channel.GetData(value)
    End Function
    Public Function Divide(ByVal no1 As Integer, ByVal no2 As Integer) As Double Implements IMyService.Divide
        Return Me.Channel.Divide(no1, no2)
    End Function
    Public Function GetChar(ByVal data As String, ByVal position As Integer) As Char Implements IMyService.GetChar
        Return Me.Channel.GetChar(data, position)
    End Function
End Class


For calling the service just create the instance of ServiceProxy and call as usual.Main advantage is the cleanliness in the code and we will have full control over the code.

No comments:

Post a Comment