3

我正在尝试按照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 服务将它们作为接口公开给客户端。

4

2 回答 2

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();
}
于 2012-07-02T11:23:50.453 回答
1

最终找到了我没有尝试过的最后一个解决方案,dpblogs的一篇文章展示了如何在服务接口的方法声明中使用属性。这最终导致我的解析方法被调用。

于 2012-07-03T13:35:21.377 回答