简体   繁体   English

如何在新的 AppDomain 中将程序集加载为仅反射?

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

I'm experienced in C# but relatively unfamiliar with the concepts of AppDomain and the like.我在 C# 方面有经验,但对AppDomain等概念相对不熟悉。 Anyway, I'm trying to get an assembly to load in a reflection-only context so I can grab all of its namespaces.无论如何,我正在尝试让程序集加载到仅反射上下文中,以便我可以获取其所有名称空间。 Here is the code I have right now (warning: PowerShell):这是我现在拥有的代码(警告:PowerShell):

function Get-Namespaces($assembly)
{
    $assemblyClass = [Reflection.Assembly]
    $winmdClass = [Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata]
    $domain = [AppDomain]::CurrentDomain

    # Since desktop .NET can't work with winmd files,
    # we have to use the reflection-only APIs and preload
    # all the dependencies manually.
    $appDomainHandler =
    {
        Param($sender, $e);
        $assemblyClass::ReflectionOnlyLoad($e.Name)
    }

    $winmdHandler =
    {
        Param($sender, $e)
        [string[]] $empty = @()
        $path = $winmdClass::ResolveNamespace($e.NamespaceName, $empty) | select -Index 0
        $e.ResolvedAssemblies.Add($assemblyClass::ReflectionOnlyLoadFrom($path))
    }

    # Hook up the handlers
    $domain.add_ReflectionOnlyAssemblyResolve($appDomainHandler)
    $winmdClass::add_ReflectionOnlyNamespaceResolve($winmdHandler)

    # Do the actual work
    $assemblyObject = $assemblyClass::ReflectionOnlyLoadFrom($assembly)
    $types = $assemblyObject.GetTypes()
    $namespaces = $types | ? IsPublic | select Namespace -Unique

    # Deregister the handlers
    $domain.remove_ReflectionOnlyAssemblyResolve($appDomainHandler)
    $winmdClass::remove_ReflectionOnlyNamespaceResolve($winmdHandler)

    return $namespaces
}

For some reason, when I'm running the function on assemblies like System.Xaml or WindowsBase I'm getting these errors:出于某种原因,当我在System.XamlWindowsBase等程序集上运行该函数时,出现以下错误:

Exception calling "ReflectionOnlyLoadFrom" with "1" argument(s): "API restriction:
The assembly 'file:///C:\Program Files (x86)\Reference Assemblies\Microsoft\
Framework\.NETFramework\v4.6.1\System.Xaml.dll' has already loaded from a
different location. It cannot be loaded from a new location within the same
appdomain."
At C:\Users\James\Code\csharp\Shims.Xaml\generate.ps1:50 char:5
+     $assemblyObject = $assemblyClass::ReflectionOnlyLoadFrom($assembl ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FileLoadException

So what I'd like to know is, how can I load the assembly in a new AppDomain?所以我想知道的是,如何在新的 AppDomain 中加载程序集? I checked MSDN but all I can find are methods like CreateInstanceAndUnwrap , which I can't/don't want to do since this is reflection-only.我检查了MSDN,但我能找到的只有CreateInstanceAndUnwrap类的方法,我不能/不想这样做,因为这只是反射。

TL;DR: How can I load assemblies in a reflection-only context in a new AppDomain? TL;DR:如何在新 AppDomain 的仅反射上下文中加载程序集? Both C# and PowerShell code samples welcome.欢迎使用 C# 和 PowerShell 代码示例。


EDIT: Here is a GitHub gist of the script I've made, so others can repro the error/test changes.编辑:是我制作的脚本的 GitHub 要点,因此其他人可以重现错误/测试更改。

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.我的解决方法是在单独的 .ps1 中执行程序集加载,并通过CMD /C调用它,这会为每个脚本调用创建一个新的 AppDomain,从而避免异常。

Parent *.ps1:父 *.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:检查-assembly.ps1:

Param(
    [Parameter(Mandatory, HelpMessage="DLL file to check: ")] 
    [string]$dllFile
)

$ass = [System.Reflection.Assembly]::LoadFrom("$dllFile")
# Check $ass

I think I've got it:我想我已经明白了:

function Load-AssemblyInNewAppDomain($assembly)
{
    $domain = [AppDomain]::CreateDomain("foo")
    $domain.DoCallback
    ({
        $loaded = [Reflection.Assembly]::Load($assembly)
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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