Assembly loading by reflection c# causes type comparison problem

36 views Asked by At

I have the following scenario in which some dll could be referenced as normal reference and also can be loaded by reflection.

I have a library with an xml configuration file which specifies what libraries have to be loaded (because not in all cases are necessary the same libraries).

The dlls are loaded as following. This is working well when the exe program does not have any of the loaded assemblies as references but in some cases those dlls could be used in the exe project as reference to use some of the message classes inside the library.

public class MessageTranslator {
    private readonly Type[] _baseTypes = new Type[] {
        typeof(MessageBase),
        typeof(MessageEventBase),
        typeof(MessageGetBase)
    };

    public void LoadAssembly(string asseblyPath) {
        var assembly = Assembly.LoadFrom(asseblyPath);
        var types = assembly.GetTypes().Where(t => t.IsClass && t.IsAbstract && _basetypes.Contains(t.BaseType));
    }
}

Exe program which has:

  • Lib.Messages.Battery as normal reference
  • Also load by reflection Library ProjectA

Library ProjectA loads assemblies by reflection

Lib.Messages.Base
Lib.Messages.Network
Lib.Messages.Battery

The problem is that Lib.Messages.Battery extends from Lib.Messages.Base and both dll are copied in bin folder of Exe file. Then when that dlls are also loaded from Library ProjectA which is in another folder, using reflection (same versions) something happens that make the _basetypes.Contains(t.BaseType) not working.

I think that this is happening because of having same dlls loaded from different folders. I have been searching and maybe I have to have different AppDomains and all references that Library ProjectA need to be loaded in separated AppDomain.

If I have all the dlls in the bin folder there is no problem and everything works well.

I have try to load Library ProjectA using new AppDomain but I'm getting an exception

Library ProjectA and any of it's dependencies could not be loaded. The system coudl not locate the specified file

This works well

var assembly = Assembly.LoadFrom(LibraryProjectAPath);
var someType = assembly.GetType("Comms.ClientWrapper");
Activator.CreateInstance(someType);

This throws mentioned exception.

var setup = AppDomain.CurrentDomain.SetupInformation;
setup.ApplicationBase = Path.GetDirectoryName(LibraryProjectAPath);
var newDomain = AppDomain.CreateDomain("newDomain", null, setup);
var assemblyName = AssemblyName.GetAssemblyName(LibraryProjectAPath);
newDomain.Load(assemblyName);

Is the AppDomain the correct workaround to solve this problems? How can I make it work? As you can see is not working correctly because the assembly loading from new AppDomain is not working.

0

There are 0 answers