Skip to content

Latest commit

 

History

History
50 lines (33 loc) · 3.59 KB

how-to-specify-a-service-binding-in-code.md

File metadata and controls

50 lines (33 loc) · 3.59 KB
description title ms.date dev_langs ms.assetid
Learn more about: How to: Specify a Service Binding in Code
How to: Specify a Service Binding in Code
03/30/2017
csharp
vb
67ab5dd8-79c1-4e62-aa75-828ea918a53a

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 xref:System.ServiceModel.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.

    [!code-csharpC_HowTo_CodeServiceBinding#1] [!code-vbC_HowTo_CodeServiceBinding#1]

  2. Implement the service contract in a service class.

    [!code-csharpC_HowTo_CodeServiceBinding#2] [!code-vbC_HowTo_CodeServiceBinding#2]

  3. In the hosting application, create the base address for the service and the binding to use with the service.

    [!code-csharpC_HowTo_CodeServiceBinding#3] [!code-vbC_HowTo_CodeServiceBinding#3]

  4. Create the host for the service, add the endpoint, and then open the host.

    [!code-csharpC_HowTo_CodeServiceBinding#4] [!code-vbC_HowTo_CodeServiceBinding#4]

To modify the default values of the binding properties

  1. To modify one of the default property values of the xref:System.ServiceModel.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.

    [!code-csharpC_HowTo_CodeServiceBinding#5] [!code-vbC_HowTo_CodeServiceBinding#5]

See also