繁体   English   中英

动态装配体选择和运行时加载

[英]Dynamic assembly selection and loading in runtime

我有一个引用Microsoft.Data.SqlXml.dll程序集( SQLXML的一部分)的应用程序。 但是在不同的计算机上,根据是实际环境还是测试环境,还是开发人员本地PC,都安装了不同版本的SQLXML 这就产生了一个问题:根据目标计算机,我必须针对正确的Microsoft.Data.SqlXml.dll程序集编译应用程序。

在Subversion中,我保留在实时环境中使用的csproj和dll文件。 当我不得不在本地测试利用Microsoft.Data.SqlXml.dll的模块时,我在项目中更改了引用,并将其还原。 但是有几次我忘了回滚更改,并签入了csproj和Microsoft.Data.SqlXml.dll ,其版本与实时服务器上安装的SQLXML不兼容。 结果,我收到了运行时错误。

我的问题是:有什么方法可以在运行时动态加载程序集? 我可以在应用程序中的某处使用switch语句,该语句将根据app.config中的条目加载正确的程序集(例如env =“ live | test | local”)? 也许还有另一种方法可以解决这个问题?

谢谢,帕维尔

从Microsoft 页面

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

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;          
}

自然,您必须更改零件//Build the path of the assembly使用所需的零件//Build the path of the assembly

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM