加载启动目录以外的DLL(Assembley)的3种方法

 net运行时,通常会从启动目录加载assembly。但是如果我们碰到下面这种情况:

一个解决方案里有两个项目,A, B,
A项目是主程序,B项目是程序集。
A项目引用了B项目,编译生成后A.exe和 b.dll默认就同在Debug目录。
由于多个exe,多个dll,所以想把exe放到自己建的一个bin目录。dll都放到自己建的lib目录。并保证exe运行时能访问到lib目录中的dll

这种情况我们该如何做呢?

方法 1: 在全局程序集缓存 (GAC) 中都安装该程序集

      这样dll就变成了全局的,所有exe都可以载入它。

方法 2: 使用 <codebase> 标记应用程序配置 (.config) 文件

<codebase> 标记指定公共语言运行库在哪里可以找到程序集。 公共语言运行库从.config 文件应用 <codebase> 标记的设置。 <codebase> 标记该设置确定版本和程序集的位置。

<configuration>
   <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
         <dependentAssembly>
            <assemblyIdentity name="MyAssembly2"  culture="neutral" publicKeyToken="307041694a995978"/>
            <codeBase version="1.0.1524.23149" href="FILE://C:/Myassemblies/MyAssembly2.dll"/>
         </dependentAssembly>
      </assemblyBinding>
   </runtime>
</configuration>

方法 3: 使用 AssemblyResolve 事件 

 当net runtime加载引用的assembly失败时,会触发AssemblyResolve 事件,AssemblyResolve 事件处理程序必须返回可以一个的 [程序集] 对象,并将公共语言运行库必须绑定到此对象。 通常,您可以使用 Assembly.LoadFrom 方法加载该程序集,然后返回该对象。

private Assembly MyResolveEventHandler(object sender,ResolveEventArgs args)
{
//This handler is called only when the common language runtime tries to bind to the assembly and fails.

//Retrieve the list of referenced assemblies in an array of AssemblyName.
Assembly MyAssembly,objExecutingAssemblies;
string strTempAssmbPath="";

objExecutingAssemblies=Assembly.GetExecutingAssembly();
AssemblyName [] arrReferencedAssmbNames=objExecutingAssemblies.GetReferencedAssemblies();

//Loop through the array of referenced assembly names.
foreach(AssemblyName strAssmbName in arrReferencedAssmbNames)
{
//Check for the assembly names that have raised the "AssemblyResolve" event.
if(strAssmbName.FullName.Substring(0, strAssmbName.FullName.IndexOf(","))==args.Name.Substring(0, args.Name.IndexOf(",")))
{
//Build the path of the assembly from where it has to be loaded.
strTempAssmbPath="C:\\Myassemblies\\"+args.Name.Substring(0,args.Name.IndexOf(","))+".dll";
break;
}

}
//Load the assembly from the specified path.
MyAssembly = Assembly.LoadFrom(strTempAssmbPath);

//Return the loaded assembly.
return MyAssembly;
}

参考资料:

How to load an assembly at runtime that is located in a folder that is not the bin folder of the application

http://support.microsoft.com/kb/837908/en-us/

< type="text/javascript">

posted @ 2009-02-04 17:26  蔡秋心  阅读(963)  评论(0编辑  收藏  举报