jeudi 26 juillet 2018

Loading static class information using reflection in dot net core

I have a .NET (framework) project which has a solution file, which contains many csproj files.

Let's say I have a class in one of my csproj, it is a simple model class but it has some annotations. I want to load the DLL containing this class, and then use reflection to retrieve information on the class. Information I need to retrieve is a list of fields (model variables) and also annotations on the object.

I was hoping I could load just the DLL for the namespace containing my model class, find the type and then use reflection to discover the stuff I need.

I'm using a dot net core app to do this, however the DLLs I am working with will be dot net framework. Unsure if this makes a difference, if it does I can switch to framework for this new project.

Here is the code I have so far to load my DLL:

var myAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(@"url to single dll");
var types = myAssembly.GetTypes();

The second line gives me this exception:

System.Reflection.ReflectionTypeLoadException - Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

If I go into the LoaderExceptions I see 80 sub-exceptions, which would suggest to me I need further DLLs loaded to be able to get any type.

System.IO.FileNotFoundException: Could not load file or assembly 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified. File name: 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral ...

To fix this, I tried to add System.Web.Mvc dll from my project to my new apps bin folder, hoping dot net would be able to find the dll in question and would remove some of the sub exceptions. This didn't work putting the dll directly in bin, or in 'bin\Debug\netcoreapp2.0'.

So the question: do I need to explicitly load all dlls my loaded dll is dependant on to be able to use reflection on a type in my desired dll? Bearing in mind I only want to load information available at compile time (fields on object, plus the string value of an annotation). Or is there a way to achieve this by loading a single dll (or perhaps sln).





Aucun commentaire:

Enregistrer un commentaire