.NET: calling the GetInterface method of the obj assembly with a common interface argument

I have the following interface:

public interface PluginInterface<T> where T : MyData { List<T> GetTableData(); } 

In a separate assembly, I have a class that implements this interface. In fact, all classes that implement this interface are in separate assemblies. The reason is to architect my application as a host plugin, where the plugin may be executed in the future, as long as they implement the above interface, and the assembled DLL files are copied to the appropriate folder.

My application detects plugins by first loading the assembly, and does the following:

 List<PluginInterface<MyData>> Plugins = new List<PluginInterface<MyData>>(); string FileName = ...;//name of the DLL file that contains classes that implement the interface Assembly Asm = Assembly.LoadFile(Filename); foreach (Type AsmType in Asm.GetTypes()) { //Type type = AsmType.GetInterface("PluginInterface", true); // Type type = AsmType.GetInterface("PluginInterface<T>", true); if (type != null) { PluginInterface<MyData> Plugin = (PluginInterface<MyData>)Activator.CreateInstance(AsmType); Plugins.Add(Plugin); } } 

The problem is that not a single line in which I get the type, using Type Type = ... , seems to work, as both seem to be null. I have a feeling that the pedigree is somehow contributing to this problem. You know why?

+4
source share
1 answer

It looks like you should use the interface name you searched for when requesting the interface:

 Type type = AsmType.GetInterface("PluginInterface`1", true); 

From MSDN :

For common interfaces, the name parameter is a malformed name, ending with a serious accent (`) and the number of type parameters. This is true both for defining common interfaces, as well as for built common interfaces. For example, to find IExample <T> or IExample <string>, search for "IExample`1".

+6
source

Source: https://habr.com/ru/post/1312112/


All Articles