Reflection application, light reflection Application
1. Multi-System database configuration through reflection
Defines the interface to reflect the value of the node configured for instantiation.
Configure App. config. (There is a rich blog on APP. config configuration. For more information, see Zhou Gong's blog)
<?xml version="1.0" encoding="utf-8" ?><configuration> <appSettings> <add key="DAL" value="FactoryInterface.Oracle"/> </appSettings></configuration>
Read the value of the key through System. Configuration. ConfigurationManager. deleetmanager. Use Configuration to add its dll to the project.
Interface Definition
namespace FactoryInterface{ interface IDAL { void insert(); }}
Program Definition
namespace FactoryInterface{ class Program { static void Main(string[] args) { string config = System.Configuration.ConfigurationManager.AppSettings["DAL"]; Console.WriteLine(config); Type t = Type.GetType(config); IDAL dal =(IDAL) System.Activator.CreateInstance(t); dal.insert(); Console.ReadKey(); } } class MySql : IDAL { public void insert() { Console.WriteLine("this data insert by MySql"); } } class Oracle : IDAL { public void insert() { Console.WriteLine("this data insert by Oracle"); } }}
Output result: