动态创建DAL层类的实例

为了可扩展性,方便以后对于代码的修改维护,使用动态创建DAL层对象。

1、首先在webconfig中的configuration下添加配置项

 <appSettings>
    <add key="IStuDAL" value="StuDAL.StudentDAL"/>
  </appSettings>

2、在工厂中创建实例

 1 namespace DALFactory
 2 {
 3     public  class DALHelper
 4     {
 5         public static IStuDAL AddStu()
 6         {
 7             //IStuDAL stu = new StudentDAL();
 8             //return stu;
 9 
10 
11             //这里应该动态创建类的实例
12             string path = ConfigurationManager.AppSettings["IStuDAL"];   //得到StuDAL.StudentDAL
13             string type = path.Split('.')[0];    //得到StuDAL
14             Assembly ab = Assembly.Load(type);
15             return  (IStuDAL)ab.CreateInstance(path);
16         }
17 
18         public static IStuDAL GetAllStudent()
19         {
20            string path=ConfigurationManager.AppSettings["IStuDAL"];
21 
22            string type = path.Split('.')[0];
23            Assembly ab = Assembly.Load(type);
24            return (IStuDAL)ab.CreateInstance(path);
25         }
26     }
27 }
View Code

注意一点
用此方法前需要在UI层中添加对DAL层引用

 

posted @ 2016-09-13 10:20  一抹嫣红  阅读(543)  评论(0编辑  收藏  举报