Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a proxy for a wcf service

Tags:

wcf

How to generate a proxy, Here is my service:

using System;

// Service.cs file
namespace FirstWcfService
{
    public class Service : IService
    {
        #region IService Members

        public string Hello()
        {
            return ("Hello WCF");
        }

        #endregion
    }
}
like image 465
np. Avatar asked Dec 23 '22 05:12

np.


2 Answers

First of all, make sure your service that you want to reference is up and running.

Then, in Visual Studio's Solution Explorer, ping "Add Service Reference":

alt text

In the dialog box that appears, type in your service address, and click on "Go":

alt text

This should connect to your service, discover the metadata, and if all goes well, you'll see your service (the service contract and its methods) in the middle part of the screen:

alt text

Before you click on "OK" too quickly - pay attention to the textbox "Namespace" in the lower left corner - you can type in a namespace in which your service reference (the classes it generates) will live. I typically use something like (project).(servicename).Adapter - choose whatever makes sense to you.

Now, in your Solution Explorer, you'll see a new icon for the service you've just referenced - when you click on the "Show all files" button on the Solution Explorer toolbar, you'll see all the files that were generated. The one where your classes live is always called Reference.cs.

alt text

When you dare to open that file :-), you'll see that you'll have a class called (yourservicename)Client which is what you need to instantiate in your client code - it will carry all the defined service methods, which you can now call from your code:

alt text

Hope this helps !

like image 106
marc_s Avatar answered Jan 16 '23 05:01

marc_s


After you have configured access to your WCF service you have two options:

Option one is to use the auto generated object

var proxy = new MyServiceProxyClient();
proxy.open();
//do work
proxy.close();

Option 2 is to use the channel factory

ChannelFactory<IMyService> channel =
   new ChannelFactory<IMyService>("bindingNameFromYourConfigFile");
IMyService client = channel.CreateChannel();

client.DoAwesomeStuff();

This is a pretty informative blog post you might like to read on when and why to use each of these methods. This screencast will help you too.

like image 37
Perpetualcoder Avatar answered Jan 16 '23 03:01

Perpetualcoder