WCF 合约返回接口会导致序列化问题吗? [英] WCF contract returning interface could cause serialization issue?

查看:21
本文介绍了WCF 合约返回接口会导致序列化问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试定义一个返回接口的 WCF 合同,如下所示:

[ServiceContract]公共接口 IMyContracts{【经营合同】IMyInterface GetData(字符串请求);}

为了让它工作,我认为我的接口 (IMyInterface) 必须实现 ISerializable 以确保实现我的接口的类可以被序列化.这意味着我必须为实现我的接口的任何类手动实现序列化.

如果使用不可序列化的类,我似乎要么使用我的接口并冒着运行时错误的风险,要么我使接口实现 ISerializable 并具有手动实现的相关麻烦.

我是否混淆了自己并遗漏了一些明显的东西?其他人如何使用 WCF 返回接口并避免此问题?

非常感谢.

解决方案

AFAIK,问题不在于序列化,而在于您返回的是抽象实体(接口).抽象是一个面向对象的概念,而不是 SOA 概念.因此,您的客户端的 wcf 堆栈可能不知道如何处理接口后面的类.如果客户端不知道接口背后的类怎么办.客户端的 WCF 堆栈必须对其进行反序列化,并且要进行反序列化,它必须知道该类.

因此,您必须通过 KnownTypeAttribute.

您也可以使用 ServiceKnownTypeAttribute 类更加灵活.不过,请记住,客户端必须知道类型,否则会出现异常.

I am trying to define a WCF contract that returns an interface, something like below:

[ServiceContract]
public interface IMyContracts
{
    [OperationContract]
    IMyInterface GetData(string request);
}

To get this to work I think my interface (IMyInterface) would have to implement ISerializable to ensure classes implementing my interface can be serialized. This then means I have to manually implement serialization for any classes implementing my interface.

It seems that either I use my interface and risk runtime errors if a class is used that is not serializable, or I make the interface implement ISerializable and have the associated hassle of manual implementation.

Am I confusing myself and missing something obvious? How have other people returned interfaces using WCF and avoided this problem?

Thanks very much.

解决方案

AFAIK, the problem is not with serialization but with the fact that you're returning abstract entity (an interface). Abstraction is an OO concept, not SOA concept. So, your client's wcf stack may not know what to do with the class behind the interface. What if the client does not know the class behind the interface. Client's WCF stack must deserialize it, and to do it, it must know the class.

So, you must make the class(es) behind the interface part of your contract, via KnownTypeAttribute.

You may also use ServiceKnownTypeAttribute class that seems to be more flexible. Still, remember that the client must know the type, or you'll get an exception.

这篇关于WCF 合约返回接口会导致序列化问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆