0

下面是一個非常短的UWP單元測試,它嘗試序列化並反序列化一個名爲Car的類,使用DataContractSerializer。我打算在UWP應用程序中使用這種類型的代碼來保存應用程序暫停時的會話狀態。因爲我不想將每種類型都添加到KnownTypes集合中,所以我從msdn博客中偷取了一個簡單的自定義DataContractResolver;它應該在序列化和反序列化在同一個應用程序中發生時工作(並因此共享類型和程序集)。當代碼與完整的.NET Framework 4.6.2一起運行時,它完全可以正常工作。但WEIRD THING是,完全相同的代碼失敗了,它是通用Windows項目的一部分,除此之外我還打開了「使用.NET Native工具鏈編譯」。UWP,.NET上的DataContractSerializer + DataContractResolver問題本機問題?

爲什麼不在UWP應用程序中使用完全相同的代碼而不使用.NET Native工具鏈? .NET Native應該會導致序列化複雜化,所以當使用.NET Native時,我的代碼只能在UWP上工作,這似乎很奇怪。如何使它在UWP應用程序上工作而無需使用.NET Native - 在DEBUG構建打開時,編譯速度顯着降低。

這裏是一個GitHub鏈接到一個完整的解決方案與單元測試。 https://github.com/jmagaram/CustomResolver

下面是單元測試代碼:

using System; 
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; 
using System.Runtime.Serialization; 
using System.Xml; 
using System.Reflection; 
using System.Collections.Generic; 
using System.IO; 

namespace ResolverTest { 
    [TestClass] 
    public class SerializerTestUniversal { 
     [TestMethod] 
     public void CanRoundtripComplexTypeWithNoKnownTypesAndCustomResolver() { 
      // prepare object for serialization 
      var car = new Car { Year = 2000, Model = "Ford" }; 
      var rootToSerialize = new Dictionary<string, object> { ["car"] = car }; 

      // serialize with DataContractSerializer and NO known types 
      // hopefully the custom DataContractResolver will make it work 
      var serializer = new DataContractSerializer(
       typeof(Dictionary<string, object>), 
       new DataContractSerializerSettings { DataContractResolver = new SharedTypedResolver() }); 
      var memoryStream = new MemoryStream(); 
      serializer.WriteObject(memoryStream, rootToSerialize); 

      // deserialize 
      memoryStream.Position = 0; 
      var output = (Dictionary<string, object>)(serializer.ReadObject(memoryStream)); 
      var outputCar = (Car)output["car"]; 

      // check that the data got roundtripped correctly 
      Assert.AreEqual(car.Year, outputCar.Year); 
      Assert.AreEqual(car.Model, outputCar.Model); 
     } 

     public class Car { 
      public int Year { get; set; } 
      public string Model { get; set; } 
     } 

     // To be used when serializing and deserializing on same machine with types defined in a shared assembly 
     // Intended to used for suspend/resume serialization in UWP apps 
     // Code from https://blogs.msdn.microsoft.com/youssefm/2009/06/05/configuring-known-types-dynamically-introducing-the-datacontractresolver/ 
     public class SharedTypedResolver : DataContractResolver { 
      public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver) { 
       return knownTypeResolver.ResolveName(typeName, typeNamespace, declaredType, null) ?? Type.GetType($"{typeName}, {typeNamespace}"); 
      } 

      public override bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { 
       if (!knownTypeResolver.TryResolveType(dataContractType, declaredType, null, out typeName, out typeNamespace)) { 
        XmlDictionary dictionary = new XmlDictionary(); 
        typeName = dictionary.Add(dataContractType.FullName); 
        typeNamespace = dictionary.Add(dataContractType.GetTypeInfo().Assembly.FullName); 
       } 
       return true; 
      } 
     } 
    } 
} 

這裏是爲了當.NET本機打開時它的工作對UWP所需的全部rd.xml文件內容。

<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata"> 
    <Application> 
    <Assembly Name="*Application*" Dynamic="Required All" /> 
    <Type Name="ResolverTest.SerializerTestUniversal.Car" Browse="Required Public" DataContractSerializer="Required All"/> 
    </Application> 
</Directives> 

最後,這是當.NET本機處於關閉狀態時發生的異常:

Result Message: Test method ResolverTest.SerializerTestUniversal.CanRoundtripComplexTypeWithNoKnownTypesAndCustomResolver threw exception: 
System.Runtime.Serialization.SerializationException: Type 'ResolverTest.SerializerTestUniversal+Car' with data contract name 'SerializerTestUniversal.Car:http://schemas.datacontract.org/2004/07/ResolverTest' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer. 

== ==修訂

我能得到它的一個工作不同的DataContractResolver。請參閱下面的代碼。我還將測試更改爲使用DataContractSerializer的新實例進行反序列化,因爲新的解析器在序列化過程中建立了狀態/信息。這些註釋說明了UWP和.NET 4.6.2對DataContractResolver的使用方式。我仍然不知道爲什麼原始代碼失敗,除非打開.NET Native。

public class SharedTypeResolver : DataContractResolver { 
    Type _mostRecentResolvedType = null; 

    // When an object is serialized using the Universal Windows Platform (as of version 
    // 5.2.2), the ResolveName method is called for each type it encounters immediately after 
    // calling TryResolveType. The Microsoft API specification says the ResolveName method is 
    // used to 'map the specified xsi:type name and namespace to a data contract type during 
    // deserialization', so it is a bit surprising this method is called during 
    // serialization. If ResolveName does not return a valid type during serialization, 
    // serialization fails. This behavior (and the failure) seems to be unique to the UWP. 
    // ResolveName is not called during serialization on the .Net Framework 4.6.2. 
    // 
    // During serialization it is difficult to force ResolveName to return a valid type 
    // because the typeName and typeNamespace do not include the assembly, and 
    // Type.GetType(string) can only find a type if it is in the currently executing assembly 
    // or it if has an assembly-qualified name. Another challenge is that the typeName and 
    // typeNamespace parameters are formatted differently than Type.FullName, so string 
    // parsing is necessary. For example, the typeNamespace parameter looks like 
    // http://schemas.datacontract.org/2004/07/namespace and the typeName parameter is 
    // formatted as className+nestedClassName. Type.FullName returns a single string like 
    // namespace.class+nestedClass. But even worse, generic types show up in ResolveName 
    // during serialization with names like 'StackOfint'. So the HACK approach I've taken 
    // here is to cache the last Type seen in the TryResolveType method. Whenever a 
    // typeNamespace appears in ResolveName that does not look like a real assembly name, 
    // return the cached type. 
    // 
    // During deserialization it is very easy for this method to generate a valid type name because the XML 
    // file that was generated contains the full assembly qualified name. 
    public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver) { 
     if (typeNamespace.StartsWith("http://schemas.datacontract.org")) { 
      // Should only happen on UWP when serializing, since ResolveName is called 
      // immediately after TryResolveType. 
      return _mostRecentResolvedType; 
     } 
     else { 
      // Should happen when deserializing and should work with all types serialized 
      // with thie resolver. 
      string assemblyQualifiedTypeName = $"{typeName}, {typeNamespace}"; 
      return Type.GetType(assemblyQualifiedTypeName); 
     } 
    } 

    public override bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { 
     _mostRecentResolvedType = dataContractType; 
     XmlDictionary dictionary = new XmlDictionary(); 
     typeName = dictionary.Add(dataContractType.FullName); 
     typeNamespace = dictionary.Add(dataContractType.GetTypeInfo().Assembly.FullName); 
     return true; 
    } 
} 

回答

0

這是由於.NETCore 5.2.2中的一個錯誤。我認爲它是在5.2.3中修復的。這個團隊的一名工程師幫助我。當我下載程序集的測試版時,它似乎工作。

https://github.com/dotnet/corefx/issues/10155

+0

Thx報告此問題並在此共享詳細信息:) –