C# 在 WCF 服务中传递接口?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/310160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing Interface in a WCF Service?
提问by Frode Lillerud
I'm experimenting with WCF Services, and have come across a problem with passing Interfaces.
我正在试验 WCF 服务,并且遇到了传递接口的问题。
This works:
这有效:
[ServiceContract]
public interface IHomeService
{
[OperationContract]
string GetString();
}
but this doesn't:
但这不是:
[ServiceContract]
public interface IHomeService
{
[OperationContract]
IDevice GetInterface();
}
When I try to compile the client it fails on the GetInterface method. I get an Exception saying that it can't convert Object to IDevice.
当我尝试编译客户端时,它在 GetInterface 方法上失败。我收到一个异常,说它无法将 Object 转换为 IDevice。
On the clientside the IHomeService class correctly implements GetString with a string as it's returntype, but the GetInterface has a returntype of object. Why isn't it IDevice?
在客户端,IHomeService 类使用字符串正确实现 GetString 作为它的返回类型,但 GetInterface 具有对象的返回类型。为什么不是IDevice?
采纳答案by Brian Genisio
You need to tell the WCF serializer which class to use to serialize the interface
您需要告诉 WCF 序列化器使用哪个类来序列化接口
[ServiceKnownType(typeof(ConcreteDeviceType)]
回答by Frode Lillerud
Thanks, it works when I changed it like this:
谢谢,当我像这样改变它时它有效:
[ServiceContract]
[ServiceKnownType(typeof(PhotoCamera))]
[ServiceKnownType(typeof(TemperatureSensor))]
[ServiceKnownType(typeof(DeviceBase))]
public interface IHomeService
{
[OperationContract]
IDevice GetInterface();
}
I also got help from this site: http://www.thoughtshapes.com/WCF/UsingInterfacesAsParameters.htm
我也从这个网站得到了帮助:http: //www.thoughtshapes.com/WCF/UsingInterfacesAsParameters.htm
回答by Myles J
I initially tried to pass an interface to a WCF method but couldn't get the code to work using the answers provided on this thread. In the end I refactored my code and passed an abstract class over to the method rather than an interface. I got this to work by using the KnownType attribute on the base class e.g.
我最初尝试将接口传递给 WCF 方法,但无法使用此线程上提供的答案使代码正常工作。最后我重构了我的代码并将抽象类传递给方法而不是接口。我通过使用基类上的KnownType 属性来实现它,例如
[DataContract]
[KnownType(typeof(LoadTypeData))]
[KnownType(typeof(PlanReviewStatusData))]
public abstract class RefEntityData : EntityData, IRefEntityData