问题
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