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

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

问题描述

我正在将一个控制台应用程序移植到 .NET 核心,它从外部库加载类型.在完整的 .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 包并附加到 Resolving 事件以强制从完整路径加载:

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(), @"binDebug
etcoreapp1.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)

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

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