MSDN.WhiteKnight - Stack Overflow answers
Ответ на "Inspect Types via MetadataLoadContext fails due to missing assembly (.NET core)"
Answer 60753752
The existing answer didn't worked for me (.NET Core 2.1). It fails with error that System.Runtime is not found. If i hardcode full path to System.Runtime, it fails for other assemblies, like System.Private.CoreLib. Also checking types via IsAssignableFrom seems not working when one type isn't from MetadataLoadContext.
The possible solution for assembly load errors is to include all BCL assemblies (all .dll files in directory returned by RuntimeEnvironment.GetRuntimeDirectory). This feels somewhat dumb, because not all of them are actually managed assemblies, but it seems to work. Here's complete example of searching types that implement interface via MetadataLoadContext:
using System; using System.IO; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; namespace MetadataLoadContextSample { class Program { static int Main(string[] args) { string inputFile = @"Plugin.dll"; string[] runtimeAssemblies = Directory.GetFiles(RuntimeEnvironment.GetRuntimeDirectory(), "*.dll"); var paths = new List<string>(runtimeAssemblies); paths.Add(inputFile); var resolver = new PathAssemblyResolver(paths); var context = new MetadataLoadContext(resolver); using (context) { Assembly assembly = context.LoadFromAssemblyPath(inputFile); AssemblyName name = assembly.GetName(); foreach (TypeInfo t in assembly.GetTypes()) { try { if (t.IsClass && t.GetInterface("IPlugin") != null) { Console.WriteLine(t.Name); } } catch (FileNotFoundException ex) { Console.WriteLine("FileNotFoundException: " + ex.Message); } catch (TypeLoadException ex) { Console.WriteLine("TypeLoadException: " + ex.Message); } } } Console.ReadLine(); return 0; } } }
Content is retrieved from StackExchange API.
Auto-generated by ruso-archive tools.