Binding can be configured either through configuration file or Programming. Let us see the binding representation in each method.
Administrative (Configuration file):
In the configuration file of the hosting application, you can add the <bindings> element inside the <system.serviceModel> element and add the properties to particular binding type. Properties corresponding to the particular binding type can be mentioned below. Name of the binding properties that you are going to use has to be mention in the end point.
binding="wsHttpBinding" bindingName="wshttpbind" contract="IMyService">
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<binding name="wshttpbind" allowCookies="true" closeTimeout="00:01:00"
In the following code, I have created the WSHttpBinding object and assign the properties which to be configured. This binding object is added to the Service endpoint for client communication. Similarly you can also create any type of binding and add to endpoint.
//Create a URI to serve as the base address
Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
ServiceHost host =
new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl);
//Create Binding to add to end point
WSHttpBinding wshttpbind = new WSHttpBinding();
wshttpbind.AllowCookies = true;
wshttpbind.CloseTimeout = new TimeSpan(0, 1, 0);
wshttpbind.ReceiveTimeout = new TimeSpan(0, 1, 0);
//Add a service endpoint
(typeof(MyCalculatorService.ISimpleCalculator), wshttpbind, "");
//Enable metadata exchange
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
//Start the Service
Console.WriteLine("Service is host at " + DateTime.Now.ToString());
Console.WriteLine("Host is running... Press key to stop");
Note: It is always good if you configure the binding properties using configuration file, because while moving to the production you no need to change in the code and recompile it. It is always good practice to represent in the configuration file.
- Always create the service with Interface->Implementation format, mention the contract in Interface.
- Define the service in Class library and refer the class library in Host project. Don’t use service class in host project.
- Change the instance mode to per call as default.
- Always catch exception using try/catch block and throw exception using FaultException < T >.
- Logging and Include exception should be enable while compiling the project in debug mode. While in production deployment disable the logging and Include exception details.