替换WCF默认序列化方式

创建类 :

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel.Description;

using System.Xml;

using System.Runtime.Serialization;

namespace Kingge.Mini.Network

{

public class NetDataContractSerializerOperationBehavior:DataContractSerializerOperationBehavior

{

        public NetDataContractSerializerOperationBehavior(OperationDescription operationDescription)

            : base(operationDescription)

        {

        }

        public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes)

        {

            return new NetDataContractSerializer(name,ns);

        }

        public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)

        {

            return new NetDataContractSerializer(name, ns);

        }

    }

}

客户端:

            using (ChannelFactory<T> factory = new ChannelFactory<T>(binding,adress))

            {

                foreach (OperationDescription op in factory.Endpoint.Contract.Operations)

                {

                    op.Behaviors.Remove<DataContractSerializerOperationBehavior>();

                    op.Behaviors.Add(new NetDataContractSerializerOperationBehavior(op));

                }

                ...... // do something

            }

服务端:

            using (ServiceHost host = new ServiceHost(obj))

            {

                foreach (ServiceEndpoint ep in host.Description.Endpoints)

                {

                    foreach (OperationDescription op in ep.Contract.Operations)

                    {

                        op.Behaviors.Remove<DataContractSerializerOperationBehavior>();

                        op.Behaviors.Add(new NetDataContractSerializerOperationBehavior(op));

                    }

                }

                host.Open();

                Console.Read();

            }

好处提高了序列化能力(例如如此可以序列化Type类型),缺点降低了数据接口的松耦合性.

你可能感兴趣的:(WCF)