【问题标题】:.Net 45 serialisation from .Net Standard 2.0 dll.Net 45 来自 .Net Standard 2.0 dll 的序列化
【发布时间】:2018-02-08 05:29:22
【问题描述】:

我有一个 .Net 标准 2.0 应用程序,它引用了 .Net45 dll 中的一些合同。我这样做的印象是,一旦这些合同对象被序列化,它们将使用 .Net45 程序集类型来完成。使用 .Net45 库(这是最终目标)对这些进行反序列化现在会出现错误:

在 JSON 'System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib],[System.String, System.Private.CoreLib]], System.Private.CoreLib 中指定的错误解析类型'

这显然是因为它试图从标准程序集类型而不是 mscorlib 中解析字符串类型。有什么方法可以实现我正在尝试的目标吗?

【问题讨论】:

  • 查看compatibility chart 了解您必须使用的 .NET 版本。 Afaik 它并不完全准确,需要 4.7 才能完全符合 .NETStandard 2.0。这是一团糟。
  • 是的,我无法理解,这是关于各种组合的第 12 次迭代!

标签: c# .net .net-standard jsonserializer .net-standard-2.0


【解决方案1】:

有很多不同的方法可以解决这个问题。

对于无法轻松转换为自定义 ISerializationBinder 的大型代码库 我已经实现了一个重定向(不是很漂亮,但它有效)

RedirectAssembly("System.Private.CoreLib", "mscorlib");

public static void RedirectAssembly(string fromAssemblyShotName, string replacmentAssemblyShortName)
{
    Console.WriteLine($"Adding custom resolver redirect rule form:{fromAssemblyShotName}, to:{replacmentAssemblyShortName}");
    ResolveEventHandler handler = null;
    handler = (sender, args) =>
    {
        // Use latest strong name & version when trying to load SDK assemblies
        var requestedAssembly = new AssemblyName(args.Name);
        Console.WriteLine($"RedirectAssembly >  requesting:{requestedAssembly}; replacment from:{fromAssemblyShotName}, to:{replacmentAssemblyShortName}");
        if (requestedAssembly.Name == fromAssemblyShotName)
        {
            try
            {
                Console.WriteLine($"Redirecting Assembly {fromAssemblyShotName} to: {replacmentAssemblyShortName}");
                var replacmentAssembly = Assembly.Load(replacmentAssemblyShortName);
                return replacmentAssembly;
            }
            catch (Exception e)
            {
                Console.WriteLine($"ERROR while trying to provide replacement Assembly {fromAssemblyShotName} to: {replacmentAssemblyShortName}");
                Console.WriteLine(e);
                return null;
            }
        }

        Console.WriteLine($"Framework faild to find {requestedAssembly}, trying to provide replacment from:{fromAssemblyShotName}, to:{replacmentAssemblyShortName}");

        return null;
    };

    AppDomain.CurrentDomain.AssemblyResolve += handler;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多