简体   繁体   English

使用Service Bus 1.0的继承类的DataContract和KnownTypes

[英]DataContract and KnownTypes for Inherited classes using Service Bus 1.0

Hi I have the following class hierarchy: 嗨,我有以下类层次结构:

public class SuperJob{
}

public class JobA:SuperJob{
}

public class JobB:SuperJob{
}

When i try to deserialise a SuperJob i get 当我尝试反序列化SuperJob时,我得到了

Expecting element 'SuperJob' from namespace 'http://schemas.datacontract.org/2004/07/...'.. Encountered 'Element'  with name 'JobA', namespace 'http://schemas.datacontract.org/2004/07/...'.

I have annotated my classes as follows: 我对我的课程进行了如下注释:

[DataContract]
[KnownType(typeof(JobA))]
[KnownType(typeof(JobB))]
public class SuperJob{
}

[DataContract]
public class JobA:SuperJob{
}

[DataContract]
public class JobB:SuperJob{
}

Not sure what i am doing wrong? 不知道我在做什么错? Any ideas how do i fix this? 任何想法我该如何解决?

Use [ServiceKnownType] attribute on your service : 在您的服务上使用[ServiceKnownType]属性:

[ServiceKnownType(typeof(JobA))]
[ServiceKnownType(typeof(JobB))]
public interface IJobService 
{
.... methods
}

Another approach would be to pass knowntypes in DataContractSerializer constructor.

List<Type> knownTypeList = new List<Type>();
knownTypeList.Add(typeof(JobA));
knownTypeList.Add(typeof(JobB));

// Create a DatatContractSerializer with the collection.
DataContractSerializer ser2 = new DataContractSerializer(
                                  typeof(SuperJob), knownTypeList);

Managed to fix this issue, there is a bug in the way the service bus instantiates the serialiser. 设法解决此问题,服务总线实例化序列化程序的方式存在一个错误。 looks like internally it instantiates the serialiser with JobA.getType(). 看起来在内部它使用JobA.getType()实例化序列化程序。 So the best way forward is to create your own DataSerializer object which uses typeOf(JobA) and pass that in both when sending the message on to the bus and reading off the bus. 因此,最好的前进方式是创建自己的DataSerializer对象,该对象使用typeOf(JobA)并在将消息发送至总线和读取总线时将其传递给两者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM