Как использовать пакет сообщений в формах xamarin - PullRequest
1 голос
/ 10 июля 2020

Мне нужно использовать MessagePack для десериализации данных, возвращаемых из веб-API (ASP. net), которые были сериализованы с использованием того же пакета.

Использован следующий код

public async static Task<T> DeserializeAsync<T>(Stream stream)
{
    if (stream == null)
    {
        throw new ArgumentNullException(nameof(stream), "Stream value cannot be null");
    }
     
    stream.Position = 0;
    T deserialized = await MessagePackSerializer.DeserializeAsync<T>(stream, MessagePack.Resolvers.ContractlessStandardResolver.Options).ConfigureAwait(false);
    return deserialized;
}

Все работало нормально в Android в режиме отладки, но в iOS и в отладочном, и в выпускном, и в Android режиме выпуска. Произошел сбой кода десериализации со следующими исключениями:

Android -> Release 

[MonoDroid]   at MessagePa07-10 18:06:01.269 I/MonoDroid(13495): MessagePack.MessagePackSerializationException: Failed to deserialize Project.Core.Models.SomeData Class value. ---> System.TypeInitializationException: The type initializer for 'FormatterCache`1' threw an exception. ---> MessagePack.Internal.MessagePackDynamicObjectResolverException: can't find public constructor. type:System.Drawing.Drawing2D.Matrix
[MonoDroid]   at MessagePack.Internal.ObjectSerializationInfo.CreateOrNull (System.Type type, System.Boolean forceStringKey, System.Boolean contractless, System.Boolean allowPrivate) [0x009a0] in <23c4c9b023514c20801c8f07fd69206c>:0 
[MonoDroid]   at MessagePack.Internal.DynamicObjectTypeBuilder.BuildType (MessagePack.Internal.DynamicAssembly assembly, System.Type type, System.Boolean forceStringKey, System.Boolean contractless) [0x00015] in <23c4c9b023514c20801c8f07fd69206c>:0 

iOS->
System.TypeInitializationException: The type initializer for 'Project.Core.Helpers.BinarySerializer' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MessagePack.Resolvers.ContractlessStandardResolver' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MessagePack.Internal.StandardResolverHelper' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MessagePack.Resolvers.DynamicEnumResolver' threw an exception. ---> System.PlatformNotSupportedException: Operation is not supported on this platform.
  at MessagePack.Internal.DynamicAssembly..ctor (System.String moduleName) [0x0001a] in <f04e2061de5c414991b8e36a20354820>:0 
  at MessagePack.Resolvers.DynamicEnumResolver..cctor () [0x00010] in <f04e2061de5c414991b8e36a20354820>:0 
   --- End of inner exception stack trace ---
  at (wrapper managed-to-native) System.Object.__icall_wrapper_mono_generic_class_init(intptr)
  at MessagePack.Internal.StandardResolverHelper..cctor () [0x00000] in <f04e2061de5c414991b8e36a20354820>:0 
   --- End of inner exception stack trace ---

Обнаружен раздел на странице MessagePack git, в котором указан способ решения этой проблемы с использованием генератора временного кода Ahead of Time Code. Я выполнил шаги, но не смог решить проблему. Также я уверен, что делаю все правильно.

Как использовать MessagePack в Xamarin.Forms. Может ли кто-нибудь, кто уже предложил мне или предоставить ссылку.

Обновление по выполненным шагам

  1. Используемая сериализация пакета сообщений одним нажатием кнопки.
  2. Установлен инструмент mp c.
  3. Используется not mp c -i "{путь к FormsProject.csproj}" -o "{путь к каталогу FormsProject}"
  4. Добавлен Созданный пакет сообщений сгенерированный класс для проекта форм.
  5. Используется следующий код в App.xaml.cs Initialize method
StaticCompositeResolver.Instance.Register(
     MessagePack.Resolvers.GeneratedResolver.Instance,
     MessagePack.Resolvers.StandardResolver.Instance

Теперь также (Операция не поддерживается в платформе) Выдается исключение. Я не совсем понимаю, что делаю здесь.

Обновление 2:

Исключение в MessagePackSerializerOptions

System.TypeInitializationException: The type initializer for 'MessagePackSerializerOptionsDefaultSettingsLazyInitializationHelper' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MessagePack.Resolvers.StandardResolver' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MessagePack.Internal.StandardResolverHelper' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MessagePack.Resolvers.DynamicEnumResolver' threw an exception. ---> System.PlatformNotSupportedException: Operation is not supported on this platform.
  at System.Reflection.Emit.AssemblyBuilder.DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/corlib/System.Reflection.Emit/AssemblyBuilder.pns.cs:129 
  at MessagePack.Internal.DynamicAssembly..ctor (System.String moduleName) [0x0001a] in <f04e2061de5c414991b8e36a20354820>:0 
  at MessagePack.Resolvers.DynamicEnumResolver..cctor () [0x00010] in <f04e2061de5c414991b8e36a20354820>:0 

Ответы [ 2 ]

1 голос
/ 14 июля 2020

Требуется установить StaticCompositeResolver.Instance по умолчанию. Вам не хватает следующего кода.

var option = MessagePackSerializerOptions.Standard.WithResolver(StaticCompositeResolver.Instance);
MessagePackSerializer.DefaultOptions = option;
0 голосов
/ 30 августа 2020

Обновление до версии MessagePack 2.1.165 или выше.

Эта проблема была исправлена ​​в пакете сообщений в версии 2.1.165. По поводу ленивой загрузки DynamicAssembly.

Ссылка на выпуск

...