When developing plug-ins, you need to use reflection, dynamically load the traversal assembly on the client, and invoke the method of each assembly.
To create a console application, first design an interface:
Public interface Isay
{
void Saysth ();
}
Create the Plugins folder under the console application, where the console's executable file and all assembly files are generated. Right-click the console item-"Properties"-"build" to set the "Output path" to the Plugins folder.
Create a Class library project Assembly1, add a reference to the console project, and create a class that implements the Isay interface:
Namespace Assembly1
{public
class Onesay:isay
{public
void Saysth ()
{
Console.WriteLine ("I Come from Assembly 1");}}
Right-key class library project assembly1--"Properties"-"Build", set "Output path" to plugins folder, and generate Class library project Assembly1.
The client needs to find all classes that implement the Isay interface in all assemblies. The basic idea is:
→ Find files for all DLL suffixes under the plugins folder
→ Traverse these files, dynamically load the assembly based on the filename
→ Iterate over the type of Isay interface implemented in an assembly and save it to a Isay type collection
→ The client traverses the collection of Isay types, calling the Isay interface method
Class program
{
static void Main (string[] args)
{
foreach (Var say in Getspeakers ())
{
say. Saysth ();
}
Static list<isay> getspeakers ()
{
list<isay> result = new list<isay> ();
Gets the plugins folder in the project root directory,
string dir = Directory.GetCurrentDirectory ();
Traverse a file in the destination folder that contains the DLL suffix
(var file in Directory.GetFiles (dir + @ "\", "*.dll"))
{
//load Assembly
var ASM = assembly.loadfrom (file);
Traverses the Type
foreach (var type in ASM) in the assembly. GetTypes ())
{
//If is the Isay interface if
(type). Getinterfaces (). Contains (typeof (Isay))
{
//Create interface type instance
var Isay = activator.createinstance (type) as Isay;
if (Isay!= null)
{result
. ADD (Isay);
}}}} return result;
}
Then create a class library project Assembly2, add a reference to the console project, and create a class that implements the Isay interface:
Namespace Assembly2
{public
class Twosay:isay
{public
void Saysth ()
{
Console.WriteLine () I am from assembly 2 ");}}
Right-key class library project assembly2--"Properties"-"Build", set "Output path" to plugins folder, and generate Class library project Assembly2.
Run the console project again.
The above C # use reflection to load multiple assemblies of the implementation method is small set to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.