This article will explain creation of custom binding in WCF services.
How to create a custom binding in WCF
services
Hello all in
this article, I will explain the steps for creating the custom binding in WCF.
What is binding in WCF?
- In WCF binding determines how the
service communicates with its client. How the end points communicates with each
other.
- WCF comes with several predefined bindings and used as per the requirement.
- The bindings determines the how
service is accessed. I.e. binding specifies,
- The
protocol used to access the service,
- Encoding
used for messages,
- Security,
- Transports
methods,
- Communication
Pattern,
- Reliability,
- Interoperability
etc.
Custom Binding
- Custom
binding is required when standard bindings do not fulfill our requirements.
- For
creating custom binding only Transport and Encoding methods are required
elements all other elements are optional.
We can
create custom binding using following two approaches
- Using the configuration file
- Create <customBinding> element in the <bindings> collection as follows :
<bindings>
<customBinding>
<binding name=”custombinding”>
<httpTransport/>
<textMessageEncoding/>
<binding>
</customBinding>
</bindings>
- Add reference to “System.ServiceModel.Channel” namespace.
- Create the instance of “BindingElementCollection” class.
- Specify the transport and encoding
methods (Since those are required. You can also specify optional elements like
security)
- Create the instance of “CustomBinding” by passing the instance
of “BindingElementCollection” class. CustomBinding class available in System.ServiceModel.Channel namespace,
used to create a custom binding from a set of binding element.
- Finally specify this binding while
adding endpoint to host instance.
Following is the sample
code:
using System.ServiceModel.Channel;
//Crating instance of ServiceHost class
ServiceHost host = new ServiceHost(typeof(MyService));
//BindingElementCollection instance
BindingElementCollection bindingElementCollection =new BindingElementCollection();
//Encoding Method
bindingElementCollection.Add(new MtomMessageEncodingBindingElement());
//Transport Method
bindingElementCollection.Add(new TCPTransportBindingElement());
//CustomBinding instance
CustomBinding customBinding = new CustomBinding(bindingElementCollection);
//Adding endpoint with custom binding to host
host.AddServiceEndpoint(typeog(IMyService),customBinding, “http://MyServer/MyService/”);