通过使用反射创建对象,废话不多说直接上代码
using System.Reflection; namespace Factory { public class DALFactory { static DALFactory() { Assembly assembly = Assembly.Load(StaticConstant.DALDllName); DALType = assembly.GetType(Constant.DALTypeName); } private static Type DALType = null; public static IBaseDAL CreateInstance() { return (IBaseDAL)Activator.CreateInstance(DALType); } } }
Constant 类:
private static string DALTypeDll = ConfigurationManager.AppSettings["DALTypeDll"]; public static string DALDllName = DALTypeDll.Split(',')[1]; public static string DALTypeName = DALTypeDll.Split(',')[0];
配置文件:
<appSettings> <add key="DALTypeDll" value="程序集.BaseDAL,程序集"/> </appSettings>
特别注意:BaseDAL是继承IBaseDAL的