.Net 45 serialisation from .Net Standard 2.0 dll

420 views Asked by At

I have a .Net standard 2.0 app that is referencing some contracts in a .Net45 dll. I was doing it this way under the impression that once these contract objects get serialised they will be done so using the .Net45 assembly types. Deserilising these using a .Net45 library (which is the end goal) is now giving the error:

Error resolving type specified in JSON 'System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib],[System.String, System.Private.CoreLib]], System.Private.CoreLib'

Which is obviously because it is trying to resolve the string type from the Standard assembly type, not from mscorlib. Is there any way of achieving what I am attempting?

1

There are 1 answers

0
Mortalus On

There are many different ways to can tackle this.

For large code-base that cannot be easily converted to a custom ISerializationBinder I have implement a redirect (not pretty but it works)

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;
}