How to load an assembly as reflection-only in a new AppDomain?

后端 未结 2 1427
北海茫月
北海茫月 2020-12-21 15:26

I\'m experienced in C# but relatively unfamiliar with the concepts of AppDomain and the like. Anyway, I\'m trying to get an assembly to load in a reflection-onl

相关标签:
2条回答
  • 2020-12-21 15:58

    I got the same exception when loading multiple assemblies for different target frameworks, but with the same identity. My workaround was to do the assembly load in a separate .ps1, and call it via CMD /C, which creates a new AppDomain for each script call, thereby avoiding the exception.

    Parent *.ps1:

    & CMD /C powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$PsScriptRoot\check-assembly.ps1" "net461\MyAssembly.dll"
    # Check exit code...
    & CMD /C powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$PsScriptRoot\check-assembly.ps1" "netcoreapp3.1\MyAssembly.dll"
    # Check exit code...
    

    check-assembly.ps1:

    Param(
        [Parameter(Mandatory, HelpMessage="DLL file to check: ")] 
        [string]$dllFile
    )
    
    $ass = [System.Reflection.Assembly]::LoadFrom("$dllFile")
    # Check $ass
    
    0 讨论(0)
  • 2020-12-21 16:13

    I think I've got it:

    function Load-AssemblyInNewAppDomain($assembly)
    {
        $domain = [AppDomain]::CreateDomain("foo")
        $domain.DoCallback
        ({
            $loaded = [Reflection.Assembly]::Load($assembly)
        })
    }
    
    0 讨论(0)
提交回复
热议问题