WCF custom serializer do not work

血红的双手。 提交于 2019-12-25 01:24:59

问题


Want to replace wcf serializer with a custom one. After googling I've found examples. But it do not work. Here is my code: Substitutor:

    internal class MySerializerSubstitutor : DataContractSerializerOperationBehavior
    {
        private static readonly MySerializer _serializer = new MySerializer();
        public MySerializerSubstitutor (OperationDescription operationDescription)
            : base(operationDescription)
        {

        }

        public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes)
        {
            return _serializer; //NEVER CALLED
        }

        public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
        {
            return _serializer; // NEVER CALLED
        }
    }

Behavior which repolace serializer

public class MySerializerBehavior : IOperationBehavior
{

.......

public void ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch)
    {
        var dcs = description.Behaviors.Find<DataContractSerializerOperationBehavior>();

        if (dcs != null)
            description.Behaviors.Remove(dcs);

        description.Behaviors.Add(new MySerializerSubstitutor(description)); //works fine
    }

.............

}

And host:

protected override void ApplyConfiguration()
{
var behavior = new MySerializerBehavior()
                foreach (var op in Description.Endpoints.SelectMany(ep => ep.Contract.Operations))
                {
                    op.Behaviors.Add(behavior);
                }
}

Whats wrong with this code?


回答1:


One problem that is immediately visible is that you cannot replace a behavior from a behavior. According to MSDN:

All of the IOperationBehavior methods pass an OperationDescription object as a parameter. This parameter is for examination only; if you modify the OperationDescription object the execution behavior is undefined.

http://msdn.microsoft.com/en-us/library/system.servicemodel.description.ioperationbehavior.aspx

I am not 100% sure what you are trying to accomplish, but here is an example that modifies properties of the serializer behavior.

http://msdn.microsoft.com/en-us/library/system.servicemodel.description.datacontractserializeroperationbehavior.aspx

If you need more customization than the properties provide you can try to replace the DataContractSerializerOperationBehavior. EDIT: Just make sure you add it before calling Open. See this article for adding a new behavior http://msdn.microsoft.com/en-us/library/ms730137.aspx



来源:https://stackoverflow.com/questions/6456816/wcf-custom-serializer-do-not-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!