Rai*_*ine 5 c# reflection .net-core
使用VS2017 RC,.NET Core
我正在尝试从文件加载程序集.此程序集的依赖项位于同一文件夹中.
我在用AssemblyLoadContext.Default.LoadFromAssemblyPath
.
我意识到LoadFromAssemblyPath
只加载请求的程序集,忽略它的依赖关系; 任何迭代装配类型的尝试都失败了System.Reflection.ReflectionTypeLoadException
.
LoaderExceptions
包含一个列表System.IO.FileNotFoundException
.
我很好奇为什么会这样,因为所有必需的文件都在同一个文件夹中.
我还尝试将所有*.dll文件加载到一个文件夹中,但有些令人惊讶地失败了System.IO.FileLoadException
.
我究竟做错了什么?
编辑:我不想依赖.deps文件(因此排除了DependencyContext).可能吗?
那么对我来说有用的是在LoadFromAssemblyPath需要依赖项时,使用Resolving事件注册句柄并按需加载所需的程序集.请注意这是我的解决方案,从几个小时的试验和错误,所以它可能不是最理想的方式.它现在适用于我.这是我的代码:
AssemblyLoadContext.Default.Resolving += (context, name) =>
{
// avoid loading *.resources dlls, because of: https://github.com/dotnet/coreclr/issues/8416
if (name.Name.EndsWith("resources"))
{
return null;
}
var dependencies = DependencyContext.Default.RuntimeLibraries;
foreach (var library in dependencies)
{
if (IsCandidateLibrary(library, name))
{
return context.LoadFromAssemblyName(new AssemblyName(library.Name));
}
}
var foundDlls = Directory.GetFileSystemEntries(new FileInfo(<YOUR_PATH_HERE>).FullName, name.Name + ".dll", SearchOption.AllDirectories);
if (foundDlls.Any())
{
return context.LoadFromAssemblyPath(foundDlls[0]);
}
return context.LoadFromAssemblyName(name);
};
}
private static bool IsCandidateLibrary(RuntimeLibrary library, AssemblyName assemblyName)
{
return (library.Name == (assemblyName.Name))
|| (library.Dependencies.Any(d => d.Name.StartsWith(assemblyName.Name)));
}
Run Code Online (Sandbox Code Playgroud)
IsCandidateLibrary()位源自那里:http: //www.michael-whelan.net/replacing-appdomain-in-dotnet-core/
我认为你可以省略这个和整个DependencyContext部分,但它充当缓存并避免一遍又一遍地重新加载相同的程序集.所以我保留了它.
归档时间: |
|
查看次数: |
4930 次 |
最近记录: |