我對C#很有經驗,但對AppDomain
之類的概念比較陌生。無論如何,我試圖讓程序集加載到僅反射的上下文中,以便我可以獲取它的所有命名空間。下面是代碼我現在所擁有的(警告:PowerShell的):如何將程序集加載爲僅反射在新的AppDomain中?
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
}
出於某種原因,當我跑步時對組件的功能類似System.Xaml
或WindowsBase
我得到這些錯誤:
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
所以我想知道的是,我怎樣才能加載在一個新的AppDomain程序集?我檢查了MSDN,但我所能找到的方法都是像CreateInstanceAndUnwrap
這樣的方法,我不能/不想這樣做,因爲這只是反射。
TL; DR:如何在新的AppDomain中僅反射上下文中加載程序集? C#和PowerShell代碼示例都歡迎。
編輯:Here是我做了腳本的GitHub的要點,以便其他人可以瑞普錯誤/測試的變化。
錯誤說,所有的組件已經加載,跳過這些和System.Reflection.Assembly.GetExecutingAssembly()抓住他們GetReferencedAssemblies() – Gusman
如果你的目標只是檢查元數據,然後有大量的替代品,如Mono.Cecil。涉及新的AppDomain和反射過於複雜。 –