To create an object instance using configuration files and reflection
In order to increase the scalability of the program and improve the configuration, it is often necessary to use configuration file + reflection to dynamically invoke the method.
The Sit class defined below contains an interface method that demonstrates how to use configuration files and reflection to invoke dynamically.
Using System;
namespace Consoleapp1.crmdatahandler
{
PublicclassSIT : crmdatahandler, iincident
{
Publicvoid createincident ()
{
Console. WriteLine ("{0} createincident", this. GetType ());
}
}
}
The configuration file is as follows:
<? XMLVersion="1.0"Encoding="utf-8" ?>
<configuration>
<appSettings>
<addkey="ClassName"value="ConsoleApp1.CRMDataHandler.SIT " />
<addkey="MethodName"value="createincident" />
</appSettings>
</configuration>
Instantiate the code and create the instantiated object in two ways:
<summary>
creating an Object instance using Activator
</summary>
Publicstaticvoid createdbyactivator ()
{
String typeName = ConfigurationManager. Appsettings.get ("ClassName");
String methodName = ConfigurationManager. Appsettings.get ("MethodName");
Type t = type. GetType (typeName);
Object instance = Activator. CreateInstance (t); //Create an instance
Object result = T.invokemember (MethodName, BindingFlags.InvokeMethod
, NULL, instance, NULL); Calling methods
T.getmethod (MethodName). Invoke (instance, null);
}
<summary>
To create an object instance using a constructor function
</summary>
Publicstaticvoid createdbyconstructor ()
{
String typeName = ConfigurationManager. Appsettings.get ("ClassName");
String methodName = ConfigurationManager. Appsettings.get ("MethodName");
Type t = type. GetType (typeName);
ConstructorInfo ci = t.getconstructor (newType[] {});
Object instance = Ci. Invoke (null);
T.getmethod (MethodName). Invoke (instance, null);
Object result = T.invokemember (methodName, BindingFlags.InvokeMethod, NULL, instance, NULL);
}
Execution Result:
C #-Create an object instance using configuration files and reflection