.net core 1.1: Type.GetType from external assembly returns null

谁说我不能喝 提交于 2021-02-04 17:53:16

问题


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.

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

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);

where delegate is:

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

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


回答1:


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.

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

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



来源:https://stackoverflow.com/questions/43918837/net-core-1-1-type-gettype-from-external-assembly-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!