In many cases, we define a functional interface that may implement many interfaces. For example, if we have a system with an alarm time notification interface, we may implement SMS notifications, there may also be email notification implementation, or other notification implementation methods. What if I load it as needed?
One way is to put all the DLL implementing this interface under a specified directory, and then load the implementation using reflection.
CodeAs follows:
Dictionary < String , Imodelcodegenerator> addintypes = New Dictionary < String , Imodelcodegenerator> (); String [] Addinassemblies = directory. getfiles (system. environment. currentdirectory, " *. Dll " ); Foreach ( String File In Addinassemblies) {Assembly addinassembly = Assembly. LoadFile (File ); Foreach (Type T In Addinassembly. getexportedtypes ()){ If (T. isclass && Typeof (Imodelcodegenerator). isassignablefrom (t) {imodelcodegenerator AI = (Imodelcodegenerator) activator. createinstance (t); addintypes. Add (AI. generatorname, AI );}}} If (Addintypes. Count = 1 ){ Foreach (Imodelcodegenerator AI In Addintypes. Values) {system. Windows. Forms. folderbrowserdialog open = New System. Windows. Forms. folderbrowserdialog (); If (Open. showdialog () = System. Windows. Forms. dialogresult. OK ){ String Strfolderpath = Open. selectedpath; AI. generatormodelcode (application. Current. properties [ " Model " ] As Conceptcontainer, strfolderpath );} Return ;}}
Of course, there are other methods. For example, there are several implementations of the configuration interface using the configuration file, and then the reflection is used to load the interface during initialization, but it is a reflection.