WCF DataContractResolver

时间:2012-07-02 11:02:11

标签: wcf datacontractserializer datacontract

我正在尝试按照http://kellabyte.com/2010/11/13/building-extensible-wcf-service-interfaces-with-datacontractresolver/的指南创建并附加DataContractSerializer。

我已经声明了序列化程序并实现了这些方法,然后使用以下代码将其附加到客户端和服务器:

public class ModuleDataContractResolver : DataContractResolver {
    public override bool TryResolveType(Type type, Type declaredType,
                                            DataContractResolver knownTypeResolver,
                                            out System.Xml.XmlDictionaryString typeName,
                                            out System.Xml.XmlDictionaryString typeNamespace) {
       ....// I return a true/false here
    }

    public override Type ResolveName(string typeName, string typeNamespace,
                                         Type declaredType, DataContractResolver knownTypeResolver) {
       ....// I return a type here
    }

-

        var endpoint = _svcHost.Description.Endpoints.FirstOrDefault()
        ContractDescription cd = endpoint.Contract;
        foreach (OperationDescription opdesc in cd.Operations) {
            DataContractSerializerOperationBehavior serializerBehavior = opdesc.Behaviors.Find<DataContractSerializerOperationBehavior>();

            if (serializerBehavior == null) {
                serializerBehavior = new DataContractSerializerOperationBehavior(opdesc);
                opdesc.Behaviors.Add(serializerBehavior);
            }

            serializerBehavior.DataContractResolver = new ModuleDataContractResolver();
        }

尽管附加了解析器,但这两种方法既不在服务上也不在客户端上调用,因此该服务抛出异常。我错过了一步吗?

更新:我并不完全相信这不是因为使用MEF返回这些类型。有问题的类型是MEF类型,它由服务检测,但仅作为客户端的接口公开,因此不会加载程序集。

这个想法是让服务加载一个MEF模块列表,然后通过这个WCF服务将它们作为接口暴露给客户端。

2 个答案:

答案 0 :(得分:1)

服务方:

foreach (OperationDescription operation in endpoint.Contract.Operations)
    {
        operation.Behaviors.Find<DataContractSerializerOperationBehavior>()
            .DataContractResolver = new ModuleDataContractResolver();
    }

客户方:

foreach (var operation in factory.Endpoint.Contract.Operations)
{
    operation.Behaviors.Find<DataContractSerializerOperationBehavior>()
        .DataContractResolver = new ModuleDataContractResolver();
}

答案 1 :(得分:1)

最终在我未尝试过的任何地方找到最后一个解决方案,dpblogs的帖子显示了如何在服务接口的方法声明中使用属性。这最终导致我的解析方法被调用。