关于程序集Assembly.Load(path)的一些注意事项

来源:互联网 发布:网络测线仪 编辑:程序博客网 时间:2024/05/21 09:28
1.每一层是否是独立的程序集(也就是独立的项目)
  因为Assembly.Load(path)这里的path必须是一个程序集的名称,而不是类命名空间的名称。


2.请检查数据层是否实现了接口。
  SQLServerDAL下面的具体类是否实现了接口的定义,如:
  
3.请检查程序集名称和命名空间不一致。
  因为Assembly.Load(path)这里的path必须是一个程序集的名称
  CreateInstance(CacheKey)这里的CacheKey其实是需要反射的类型全名(包括命名空间的全路径)。
 所以,尽量让程序集名称和命名空间一致,这样的得到的类型全名=程序集名称+类名。
 否则,你需要把CacheKey换成实际的类型全名。
       

4.请检查BLL层是否添加了SQLServerDAL的项目引用。

》》》》》》》》》》》》》》》》》》》》》》》》》》

《《《《《《《《《《《《《《《《《《《《《《《《《《

方式一:通过类名来生成对象(优势:方便;劣势:不能以递增方式增加需转化成对象的类文件,即每次发布需整个项目重新编译)经测试正确 

public class FruitFactory 

 public IFruit MakeFruit(string Name) 
 { 
  IFruit MyFruit = null; 
  try 
  { 
   Type type = Type.GetType(Name,true); 
   MyFruit = (IFruit)Activator.CreateInstance(type); 
  } 
  catch (TypeLoadException e) 
   Console.WriteLine("I dont know this kind of fruit,exception caught - {0}" ,e.Message); 
   return MyFruit; 
 } 



方式二:通过反射(需提供文件路径,类名;优势:可以以递增文件的方式发布程序;劣势:生成文件麻烦)未测试 
/// <summary> 
        /// 创建对象(外部程序集) 
        /// </summary> 
        /// <param name="path">文件路径</param> 
        /// <param name="typeName">类型名</param> 
        /// <returns>创建的对象,失败返回 null</returns> 
        public static object CreateObject(string path, string typeName) 
        { 
            object obj = null; 
            try 
            { 

                obj = Assembly.Load(path).CreateInstance(typeName); 
            } 
            catch (Exception ex) 
            { 
                Debug.Write(ex); 
            } 

0 0