Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

How to: Specify a Service Binding in Code

In this example, an ICalculator contract is defined for a calculator service, the service is implemented in the CalculatorService class, and then its endpoint is defined in code, where it is specified that the service must use the BasicHttpBinding class.

It is usually the best practice to specify the binding and address information declaratively in configuration rather than imperatively in code. Defining endpoints in code is usually not practical because the bindings and addresses for a deployed service are typically different from those used while the service is being developed. More generally, keeping the binding and addressing information out of the code allows them to change without having to recompile or redeploy the application.

For a description of how to configure this service using configuration elements instead of code, see How to: Specify a Service Binding in Configuration.

To specify in code to use the BasicHttpBinding for the service

  1. Define a service contract for the type of service.

    public interface ICalculator
       double Add(double n1, double n2);
       double Subtract(double n1, double n2);
       double Multiply(double n1, double n2);
       double Divide(double n1, double n2);
  2. Implement the service contract in a service class.

    public class CalculatorService : ICalculator
       public double Add(double n1, double n2)
          return n1 + n2;
       public double Subtract(double n1, double n2)
          return n1 - n2;
       public double Multiply(double n1, double n2)
          return n1 * n2;
       public double Divide(double n1, double n2)
          return n1 / n2;
  3. In the hosting application, create the base address for the service and the binding to use with the service.

    // Specify a base address for the service
    String baseAddress = "http://localhost/CalculatorService";
    // Create the binding to be used by the service.
    BasicHttpBinding binding1 = new BasicHttpBinding();
  4. Create the host for the service, add the endpoint, and then open the host.

    using(ServiceHost host = new ServiceHost(typeof(CalculatorService)))
        host.AddServiceEndpoint(typeof(ICalculator),binding1, baseAddress);

To modify the default values of the binding properties

  1. To modify one of the default property values of the BasicHttpBinding class, set the property value on the binding to the new value before creating the host. For example, to change the default open and close timeout values of 1 minute to 2 minutes, use the following.

    TimeSpan modifiedCloseTimeout = new TimeSpan(00, 02, 00);
    binding1.CloseTimeout = modifiedCloseTimeout;

See Also

© 2007 Microsoft Corporation. All rights reserved.
Last Published: 2010-03-21

Community Additions

© 2015 Microsoft