Deploy a Custom WCF into SharePoint2010—Part 2
In the last post of this series, I showed you how to create and deploy custom WCF to SharePoint. In this post, I will show you how to consume the custom WCF service in a console application the right way. You can download the complete source code here.
The easiest way to consume a WCF is to add a service reference using visual studio and following the wizard visual studio will generate the necessary proxy for you. You can check my previous blog post here for details of this approach.
However, I will consider this approach as the bad way of consuming a Custom WCF services assuming both the services and client are using .net and WCF. The reasons are as below:
- Every time you add service reference, visual studio generates the necessary service interface and data contracts in your application. So you have multiple copies of the same files in different places.
- Because you have multiple copies of the same files in different places, every time you update your services you need to update your services references and redeploy your solution.
- After you add the service references, visual studio add app.config files in your application and in your app.config visual studio add unnecessary amount of default attributes in the system.serviceModel section.
After you understand why it is bad to just add service reference to consume WCF services, you might ask what is the right way of consuming the WCF services? If you have used the new SharePoint client object model, you know that the client object model talk to SharePoint using WCF services, the way you use the client object model for console app is to add the Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime dlls to the application and you are all set to communicate with WCF services from SharePoint. So how can we consume the WCF services in the same as the Client object model? You need to do the following:
- You need to separate your WCF services in 3 separate projects (dlls) as specified in the last post, all service contract in a project, all service implementations in a project, all data contract in another project.
- Create forth project called BestPracticeClient for WCF client, in this project you need to references your Service contract project and data contract project and create WCF client using ChannelFactory.
- Create a console app references the BestPracticeClient , Service contract and data contract project dlls and you can consume the WCF services the same way as you do for SharePoint client object model.
You can download the complete source code here.