Wednesday, July 22, 2015

WCF Proxy generation - Add Reference to website


In our previous discussions, we discussed what about A.B.C. of WCF services and types of contracts in WCF. Continuing on the same lines, we will now discuss how we can generate the wcf proxy by adding the service reference in our project. If you have missed the series, then here are the links for the series:
  1. About the A.B.C. of WCF Service
  2. Types of Contracts in WCF
In this article, we will discuss about the concept of how we can generate the proxy for a service to use it in a client application. 
So let's start by adding a new application of Console type.

Next, we add another project to the solution, of type WCF Service Application.

We remove the default methods generated and add a simple method GetSum, to return sum of two numbers. So our interface implementation will be:

 
namespace TestService
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        Int32 GetSum(Int32 a, Int32 b);
    }
}
and our service implementation will be like:


namespace TestService
{
    public class Service1 : IService1
    {
        Int32 IService1.GetSum(int a, int b)
        {
            return a + b;
        }
    }
}

 
Next, in order to use this service in our client application, we will right click on project and select the option 'Add Service Reference'.

This will open up a window, where we can add the url of the service, where it is currently hosted. In case of current application, click on 'Discover' and it will automatically get the current service in the solution. You can expand the service and see the methods available. In case of any issues in your service, it will not be able to locate any service.

Provide a namespace and click Ok. This will add the service reference in the client project. To use the service, add the ServiceClient namespace on the project and the service can be accessed by the name as Service1Client. Use this service client instance to access the service methodsIn our case, it is GetSum method.

Run the code and see the results.

Easy to use, isn't it. Happy coding...!!!

1 comment:

  1. Nice article...a video demonstration would be great.

    ReplyDelete