wcf自定义绑定

一,创建自定义绑定

有时候我们需要创建自己的绑定,这在很多情况下不是出于特殊的安全要求和使用的传输协议。为了创建自定义的绑定,需要建立一组绑定元素。绑定元素是由System.ServiceModel.Channels.BindingElement派生而来的。

代码1,使用HTTP传输协议和Binary编码格式的自定义绑定:

  <bindings>

      <customBinding>

        <binding name="binHttp">

          <binaryMessageEncoding />

          <httpTransport />

        </binding>

      </customBinding>

   </bindings>

 

除了用配置方式创建一个自定义绑定,也可以采用编程方式。

代码2,用编程方式配置一个自定义绑定:

    class Program

    {

        static void Main(string[] args)

        {

            CustomBinding binding = new CustomBinding();

            binding.Elements.Add(new BinaryMessageEncodingBindingElement());

            binding.Elements.Add(new HttpTransportBindingElement());



            ServiceHost host = new ServiceHost(typeof(CarRentalService));

            ServiceEndpoint serviceEndpoint =

                host.AddServiceEndpoint(typeof(ICarRentalService),

                    binding,

                    "http://localhost:8080/CarRentalService");



            try

            {

                host.Open();



                Console.WriteLine("The car rental service is up and listening on the following addresses:");

                foreach (var item in host.Description.Endpoints)

                {

                    Console.WriteLine("> [{0}] {1}", item.Binding.Name, item.Address.Uri.ToString());

                }

                Console.ReadLine();



                host.Close();

            }

            catch (CommunicationException ex)

            {

                host.Abort();

                Console.WriteLine(ex);

            }

            catch (TimeoutException ex)

            {

                host.Abort();

                Console.WriteLine(ex);

            }

            catch (Exception ex)

            {

                host.Abort();

                Console.WriteLine(ex);

            }

        }

    }

 

二,重用自定义绑定

有时,可能需要创建一个能够重复用于不同解决方案的自定义绑定。由于每个绑定都派生于System.ServiceModel.Channels.Binding这个抽象基类,我们只需建立自己的绑定类,并实现CreateBindingElement方法即可实现此目的。

代码1,由基类Binding创建一个可重用的自定义绑定:

    public class NetTcpTextBinding : Binding

    {

        private TcpTransportBindingElement transport;

        private TextMessageEncodingBindingElement encoding;

        public NetTcpTextBinding()

            : base()

        {

            this.Initialize();

        }

        public override BindingElementCollection CreateBindingElements()

        {

            BindingElementCollection elements = new BindingElementCollection();

            elements.Add(this.encoding);

            elements.Add(this.transport);

            return elements;

        }

        public override string Scheme

        {

            get { return this.transport.Scheme; }

        }

        private void Initialize()

        {

            this.transport = new TcpTransportBindingElement();

            this.encoding = new TextMessageEncodingBindingElement();

        }

    }

代码2,使用NetTcpTextBing绑定:

      NetTcpTextBinding binding = new NetTcpTextBinding();



      ServiceHost host = new ServiceHost(typeof(Service1));

      host.AddServiceEndpoint(typeof(IService1),

                binding,

                "net.tcp://localhost:10101/IService");



      host.Open();

如果需要通过配置文件使用自定义绑定,必须先扩展BindingCollectionElement抽象基类,然后再实现需要的方法。
代码3,实现NetTcpTextBindingCollectionElement:

namespace ConsoleApplication1

{

    public class NetTcpTextBindingCollectionElement : BindingCollectionElement

    {

        public override Type BindingType

        {

            get { return typeof(NetTcpTextBinding); }

        }



        public override ReadOnlyCollection<IBindingConfigurationElement>ConfiguredBindings

        {

            get

            {

                return new ReadOnlyCollection<IBindingConfigurationElement>(new List<IBindingConfigurationElement>());

            }

        }



        public override bool ContainsKey(string name)

        {

            throw new NotImplementedException();

        }



        protected override Binding GetDefault()

        {

            return new NetTcpTextBinding();

        }



        protected override bool TryAdd(string name, Binding binding, Configuration config)

        {

            throw new NotImplementedException();

        }

    }

}

 

现在,如果要在配置文件中使用自定义绑定NetTcpTextBinding,就必须用绑定扩展(<bindingExtensions>)配置NetTcpTextBindingCollectionElement元素。总之,如果要在配置文件中使用自定义绑定,就需要先进行定义。
代码4,在配置文件中使用自定义绑定NetTcpTextBinding:

  <system.serviceModel>

    <services>

      <service name="WcfServiceLibrary2.Service1">

        <endpoint address="net.tcp://localhost:10101/IService"

                  binding="netTcpTextBinding"

                  contract="WcfServiceLibrary2.IService1">

        </endpoint>

      </service>

    </services>

    <extensions>

      <bindingExtensions>

        <add name="netTcpTextBinding" type="ConsoleApplication1.NetTcpTextBindingCollectionElement, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />

      </bindingExtensions>

    </extensions>

  </system.serviceModel>

 

2013-03-30

 

你可能感兴趣的:(WCF)