• Publisert
  • 1 min

How to instantiate a WCF service client.

Never instanciate a WCF service client with an empty BasicHttpBinding contructor. This will disable you from being able to configure your service through web.config.

It is very easy. Browsing the WCF service, will tell you how to create a proxy class you can use to call the service. Instantiate this proxy client in your code, and call any method you like in the service.
The proxy class is generated with many constructor overloads. Always use the empty constructor, this will enable you to use all the default configuration options delivered through WCF.

Example on how not to write your client code:
MyServiceClient client = new MyServiceClient(new BasicHttpBinding(), new EndpointAddress("http://../MyService.svc"));
client.MyMethod();
The code will work. MyMethod will be called, and default .NET vealue for a WCF service is applied. The problem is, you will not be able to configure your service through web.config. Since you did not give your bind any name (new BasicHttpBinding()).

You should call the service like this:

MyServiceClient client = new MyServiceClient();
client.MyMethod();

But this code will not work before a client endpoint is added to web.config (or app.config). Multiple endpoints can be set (for multiple services) in web.config. WCF will decide witch to use, based on the contract attribute set on the endpoint. MyServiceClient is a proxy class genereated by the .NET wcf tool, and the System.ServiceModel.ServiceContractAttribute.ConfigurationName is set to describe the contract name.

  <system.serviceModel>
    <client>
      <endpoint address="http://../MyService.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IContractName"
                contract="IContractName" />
    </client>
  </system.serviceModel>

Now the code above will work, and run with the default .NET WCF configuration. It now has its endpoint adress! To change the default .NET WCF configuration, you can add an optional Binding element to the serviceModel section, like this:

  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IContractName" maxBufferSize="33554432" maxBufferPoolSize="524288" maxReceivedMessageSize="33554432" />
      </basicHttpBinding>
    </bindings>

Note that the name of the binding matches the bindinConfigurationName of the endpoint!

Lesson: Never instantiate a WCF service client with an empty BasicHttpBinding constructor. This will disable you from configuring your service in web.config. Since you did not provide a name for the binding.