简体   繁体   中英

How to use CSharpScript with 'globals' type from a DLL which is dynamically loaded into custom collectible AssemblyLoadContext

Script evaluation code snippet:

        using (var loader = new InteractiveAssemblyLoader())
        {
            var script = CSharpScript.Create<TDataType>(
           code: expr,
           options: ScriptOptions.Default.AddImports(globals.GetType().Namespace)
                                         .AddReferences(refAssemblies),
           globalsType: globals.GetType(),
           assemblyLoader: loader);

            return script.RunAsync(globals).Result.ReturnValue;
        }

The code-analysis assemblies and the globals-type assembly are loaded into the same Collectible AssemblyLoadContext... Also tried adding references/imports explicitly through the ScriptOptions but get the same following error:

Inner Exception 1: InvalidCastException: [A]TestLibrary.TestClass cannot be cast to [B]TestLibrary.TestClass. Type A originates from 'TestLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location '...\TestLibrary.dll'. Type B originates from 'TestLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location '...\TestLibrary.dll'.

It seems the assembly loader is loading twice TestLibrary in your dynamic code, you can avoid that resolving manually the assembly (beware that TestLibrary must be the same version in both projects)

//Somewhere in your startup code:
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

static Assembly MyResolveEventHandler(object sender, AssemblyLoadEventArgs args)         
{
    //First time it will be null and the resolver will load it from the default path, the succesive requests to load the library will return the already loaded assembly.
    if(args.Name == "TestLibrary")
        return AppDomain.CurrentDomain.GetAssemblies().Where(a => a.Name == args.Name).FirstOrDefault(); 

    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM