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

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

问题描述

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

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

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

为了实现这一点,我想我的界面( IMyInterface )必须实现 ISerializable ,以确保可以序列化实现我的接口的类。这意味着我必须为实现我的接口的任何类手动实现序列化。

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.

似乎我使用我的接口并冒险运行时错误如果使用的是类不可序列化,或者我使接口实现 ISerializable 并且有相关的手动实现麻烦。

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.

我是否感到困惑我自己也错过了明显的东西其他人如何使用WCF返回接口并避免了这个问题?

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

非常感谢。

推荐答案

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

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.

因此,您必须在合同的接口部分后面创建类,通过 KnownTypeAttribute

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

您也可以使用 ServiceKnownTypeAttribute 类似乎更灵活。不过,请记住,客户必须知道类型,否则您将获得例外。

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天全站免登陆