.net core 1.1:来自外部程序集的Type.GetType返回null [英] .net core 1.1: Type.GetType from external assembly returns null

查看:63
本文介绍了.net core 1.1:来自外部程序集的Type.GetType返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将控制台应用程序移植到.NET Core,该应用程序从外部库中加载类型.在程序集位于与可执行文件相同的文件夹中的情况下,在完整的.NET Framework中,使用 Type.GetType("typename,assemblyname")即可工作.

I'm porting a console app to .NET core which load types from external libraries. In full .NET Framework using Type.GetType("typename, assemblyname") works when the assembly is located in the same folder that executable.

在.NET Core中,无论我将库放在哪里,它都将返回null.

In .NET Core, it returns null, wherever I place the library.

作为一种解决方法,我已经安装了 System.Runtime.Loader 程序包,并附加了 Resolvening 事件以强制从完整路径进行加载:

As a workaround I've installed the System.Runtime.Loader package and attached to Resolving event to force the loading from a full path:

AssemblyLoadContext.Default.Resolving += Default_Resolving;
type = Type.GetType(value);

代表在哪里:

private static Assembly Default_Resolving(AssemblyLoadContext context, AssemblyName assembly)
{
    return context.LoadFromAssemblyPath(Path.Combine(Directory.GetCurrentDirectory(), @"bin\Debug\netcoreapp1.1",  $"{assembly.Name}.dll"));
}

问题是:加载外部程序集时,.NET Core在哪里寻找?

The question is: where does .NET core looks for when loading an external assembly?

推荐答案

这花了我很长时间才能解决.默认情况下,动态加载仅从执行目录发生.静态负载完全有能力进入nuget包缓存(这是.runtimeconfig.json和.deps.json的目的),但是如果您不链接目标dll,它将不会在那里.

This took me ages to work out. Dynamic loads only happen from the execution directory by default. Static loads are quite capable of walking into your nuget package cache (this is what .runtimeconfig.json and .deps.json are for), but if you didn't link the target dll it won't be there.

您确实真的不想从当前目录加载;这很可能是一个不安全的地方,无法从其中加载dll.

You really really don't want to load from the current directory; it's quite possibly a place unsafe to load dlls from.

要获取您的加载路径: System.IO.Path.GetDirectoryName(typeof(myclassname).GetTypeInfo().Assembly.Location)

To get your load path: System.IO.Path.GetDirectoryName(typeof(myclassname).GetTypeInfo().Assembly.Location)

这篇关于.net core 1.1:来自外部程序集的Type.GetType返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆