Reliable service collection: serialization

Values ​​of a reliable collection (Queue) store some complex type SomeUnit.

I marked it as [DataContract], and its members as [DataMember]well as added an attribute [KnownType(typeof(SomeUnit))]on top of it.

SomeUnit seems to be serialized, but then the deserialization exception is thrown:

The element 'urn: ServiceFabric.Communication: item' contains data from a type that maps to the name ' http://schemas.datacontract.org/2004/07/RP.Core:SomeUnit '. deserializer does not know any type that maps to this name. Consider using a DataContractResolver if you are using a DataContractSerializer or add a type matching "SomeUnit" to a list of known types — for example, using the KnownTypeAttribute attribute or by adding it to the list of known types passed to the serializer.

How can i solve this?

+4
source share
2 answers

- , , .

, , SomeUnit.

// Using reliable collection with a base item type
IReliableQueue<BaseClass> myQueue = ...;

// Store derived item in the queue
SomeUnit myData = ...; // SomeUnit inherit from BaseClass
await myQueue.EnqueueAsync(txn, myData); // OK to store but won't deserialize!

Deserializer , BaseClass, SomeUnit.

, KnownTypeAttribute , , .

[DataContract]
[KnownType(typeof(SomeUnit))]
public class BaseClass
{
    ...
}

[DataContract]
public class SomeUnit : BaseClass
{
    ...
}

[KnownType] . :

№1

- .

[DataContract]
[KnownType(typeof(SomeUnit))]
public class Wrapper
{
    [DataMember]
    public IUnit Value { get; set; }
}

[DataContract]
public class SomeUnit : IUnit
{
    ...
}

№ 2

DataContractSerializer.

, , , .

№ 3

(app.config) .

+5

, , KnownType ( , ), , :

[DataContract]
[KnownType("GetKnownTypes")]
public abstract class Event
{
    [DataMember]
    public DateTime AtTime { get; private set; }

    public Event()
    {
        AtTime = DateTime.Now;
    }

    private static Type[] GetKnownTypes()
    {
        return typeof(Event).Assembly.GetTypes()
            .Where(x => x.IsSubclassOf(typeof(Event)))
            .ToArray();
    }
}
+2

Source: https://habr.com/ru/post/1619137/


All Articles