How to load the assembly correctly

I am developing a system with plugins that loads assemblies at runtime. I have a common interface library that I share between the server and its plugins. But, when I execute LoadFrom for the plugin folder and try to find all types that implement the common IServerModule interface, I get an exception at runtime:

The type 'ServerCore.IServerModule' exists as in 'ServerCore.dll' and 'ServerCore.dll'

I load plugins as follows:

 foreach (var dll in dlls) { var assembly = Assembly.LoadFrom(dll); var modules = assembly.GetExportedTypes().Where( type => (typeof (IServerModule)).IsAssignableFrom(type) && !type.IsAbstract && !type.IsGenericTypeDefinition) .Select(type => (IServerModule)Activator.CreateInstance(type)); result.AddRange(modules); } 

How can I deal with this problem?

I will be grateful for any help

+6
source share
2 answers

Well, my solution is ugly, but it works, and I will continue MEF in the future (maybe). At the moment, I added this thing:

 if(Path.GetFileNameWithoutExtension(dll)==Assembly.GetCallingAssembly().GetName().Name) continue; 

Thanks everyone for the amazing answers.

EDIT: I came up with a more elegant solution, here it is:

 var frameworkAssemblies = from file in new DirectoryInfo(frameworkDirectory).GetFiles() where (file.Extension.ToLower() == ".dll" || file.Extension.ToLower() == ".exe") && !AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetName().Name).Contains(file.GetFileNameWithoutExtension()) select Assembly.LoadFrom(file.FullName); 
0
source

Check the dll problems and its dependencies. Most likely, it pulls ServerCore.dll from a different version of .NET than your main application.

I recommend you use MEF if you want to make plugins.

+3
source

All Articles