The problem : Creating WCF proxy in Silverlight without using the add service reference and it’s auto generated code
It was a debate that whether we can call a WCF service from Silverlight without using “Add Service Reference” menu item.In WPF or in the other .Net environments it is easy.We just need to refer the contracts dll and write a class which inherits from ClientBase.But this is Silverlight - A different runtime.
A Normal WCF service reference with all the generated code files
There were 3 opinions.Not at all possible,Possible with less amount of code,Possible if we create all those classes by our own.Just avoid the last one because that doesn’t give us any benefit as it is just making the process manual.
One of my Colleagues started research on that and was able to achieve the same.I am just sharing the idea.
Solution : We can achieve the same using contract interface,proxy class and a custom eventargs class
First of all there are no changes at the server side.Only 3 types we are going to write at client side which will be present in the reference.cs file if you create the proxy using “Add Service Reference” Dialog.
There will be a question for sure.Why are we writing the code which is being auto generated ? Why don’t we create a reference using the dialog and copy paste the reference.cs code?
The answer for both the questions is same.You can create reference using the dialog and get the code from reference.cs.That is enough.
- Can avoid huge amount of code which is auto generated.
- This is acting as a separate layer and can encapsulate operations here in future.
Lets take example of implementing a DataService with one method GetData which returns a string.Don’t bother about the server side.Use the same.Below are the steps to perform at client side ie Silverlight side.
- Create interface IDataService
- Decorate with ServiceContract attribute.
- Add method BeginGetData.Decorate it with OpertionContract and Set AsyncPattern to True.
- Add Method EndGetData.
- Create eventArgs class deriving from System.ComponentModel.AsyncCompletedEventArgs
- Add required properties to pass values.
- Create class DataServiceProxy derived from ClientBase which Implements IDataService.Write constructors.Implement methods.Write delegates and event which communicate back to the caller.
Uploaded a sample which does the same.