C on reflection loading

  • 2020-05-07 20:17:19
  • OfStack

Three assemblies:
Main assembly: BaseApp.exe
Interface assembly: IBaseApplication
Plug-in assembly: TestAttri
=======================================================================================
In the interface program:
Interface: IApp
Property definition: ModuleAttribute
 
public interface IApp : IMothed 
{ 
void ParentForm(IApp frm); 
} 
namespace IBaseApplication.Attributes 
{ 
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = true, Inherited = false)] 
public class ModuleAttribute : Attribute 
{ 
public string IdName { get; set; } 
public string ModuleName { get; set; } 
public Type ModuleType { get; set; } 
//public string AsmName { get; set; } 
//public string ClassName { get; set; } 
public string Description { get; set; } 
} 
} 

In the plug-in assembly:
The AssemblyInfo class in the plug-in assembly is identified as follows
 
[assembly: IBaseApplication.Attributes.Module(ModuleType = typeof(UserControl1), IdName = "be4d9a5b-0455-4e9d-a255-25122b80bef1-UserControl1", ModuleName = "UserControl1", Description = "")] 
[assembly: IBaseApplication.Attributes.Module(ModuleType = typeof(UserControl2), IdName = "be4d9a5b-0455-4e9d-a255-25122b80bef1-UserControl2", ModuleName = "UserControl2", Description = "")] 

There are two modules as follows
 
namespace TestAttri 
{ 
public partial class UserControl1 : UserControl, IApp 
{ 
 ...  
} 
} 
namespace TestAttri 
{ 
public partial class UserControl2 : UserControl, IApp 
{ 
 ...  
} 
} 

=================================================================================================
In the main assembly:
Put the plugin to: Application.StartupPath + "\\Plus"
The interface assembly "IBaseApplication" is referenced
 
/// <summary> 
///  Gets the plug-in file name  
/// </summary> 
/// <returns></returns> 
public string[] GetPlusFiles() 
{ 
return System.IO.Directory.GetFiles(Application.StartupPath + "\\Plus"); 
} 
/// <summary> 
///  Load the plug-in  
/// </summary> 
public void LoadPluFiles() 
{ 
string[] files = GetPlusFiles(); 
Assembly assembly = Assembly.GetCallingAssembly(); 
foreach (string file in files) 
{ 
ModuleAttribute[] attributes = Assembly.LoadFile(file).GetCustomAttributes(typeof(ModuleAttribute), false) as ModuleAttribute[]; 
foreach (ModuleAttribute attribute in attributes) 
{ 
string m = attribute.ModuleType.FullName; 
string m1 = attribute.ModuleType.Assembly.GetName().Name; 
object obj = Activator.CreateInstance(attribute.ModuleType); 
if (obj is IApp) 
{// The interfaces of the two modules could not be identified.  
} 
} 
} 
} 

Related articles: