Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 958
Farlop Avatar asked May 11 '17 14:05

Farlop


1 Answers

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)

like image 172
Joshua Avatar answered Oct 17 '22 03:10

Joshua