You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

serialization.md 2.1 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # Serialization
  2. We provide the `ISerializer` interface to support serialization of messages. By default, json is used to serialize messages and store them in the database.
  3. ## Custom Serialization
  4. ```C#
  5. public class YourSerializer: ISerializer
  6. {
  7. Task<TransportMessage> SerializeAsync(Message message)
  8. {
  9. }
  10. Task<Message> DeserializeAsync(TransportMessage transportMessage, Type valueType)
  11. {
  12. }
  13. }
  14. ```
  15. Then register your implemented serializer in the container:
  16. ```
  17. services.AddSingleton<ISerializer, YourSerializer>();
  18. // ---
  19. services.AddCap
  20. ```
  21. ## Message Adapter (removed in v3.0)
  22. In heterogeneous systems, sometimes you need to communicate with other systems, but other systems use message objects that may be different from CAP's [**Wrapper Object**](../storage/general.md#_7). This time maybe you need to customize the message wapper.
  23. CAP provides the `IMessagePacker` interface for customizing the [**Wrapper Object**](../storage/general.md#_7). Custom MessagePacker usually packs and unpacks the `CapMessage` In this process you can add your own business objects.
  24. Usage :
  25. ```csharp
  26. class MyMessagePacker : IMessagePacker
  27. {
  28. private readonly IContentSerializer _serializer;
  29. public DefaultMessagePacker(IContentSerializer serializer)
  30. {
  31. _serializer = serializer;
  32. }
  33. public string Pack(CapMessage obj)
  34. {
  35. var myStructure = new
  36. {
  37. Id = obj.Id,
  38. Body = obj.Content,
  39. Date = obj.Timestamp,
  40. Callback = obj.CallbackName
  41. };
  42. return _serializer.Serialize(myStructure);
  43. }
  44. public CapMessage UnPack(string packingMessage)
  45. {
  46. var myStructure = _serializer.DeSerialize<MyStructure>(packingMessage);
  47. return new CapMessageDto
  48. {
  49. Id = myStructure.Id,
  50. Timestamp = myStructure.Date,
  51. Content = myStructure.Body,
  52. CallbackName = myStructure.Callback
  53. };
  54. }
  55. }
  56. ```
  57. Next, add the custom `MyMessagePacker` to the service.
  58. ```csharp
  59. services.AddCap(x =>{ }).AddMessagePacker<MyMessagePacker>();
  60. ```