动态加载库 [英] Loading library dynamically

查看:106
本文介绍了动态加载库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下项目结构:

  1. Web API
  2. 类库 A
  3. 类库 B
  4. 类库 C

这些是项目之间的引用

  • Web API 直接引用 A B
  • B 直接引用 C
  • Web API directly references A and B
  • B directly references C

C 具有一种方法,该方法需要确保加载 A 以便通过反射使用其中定义的类型.

C has a method which needs to ensure that A is loaded to use, by reflection, a type defined in it.

我的代码实际上如下所示

My code actually is like the following

public class C {
    public void MethodCallingBType( string fullClassName ) {
        //e.g. "MyNamespace.MyType, MyNamespace"
        string[] parts = fullClassName.Split( ',' );
        var className = parts[0].Trim();
        var assemblyName = parts[1].Trim();
        if ( !string.IsNullOrEmpty( assemblyName ) && !string.IsNullOrEmpty( className ) ) {
            string assemblyFolder = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location );
            string assemblyPath = Path.Combine( assemblyFolder, assemblyName + ".dll" );
            if ( File.Exists( assemblyPath ) ) {
                Assembly assembly = Assembly.LoadFrom( assemblyPath );
                Type type = assembly.GetType( className );
                result = Activator.CreateInstance( type ) as IInterfaceRunner;
            }
        }
    }
}

此代码实际上不起作用,因为 Path.GetDirectoryName 函数不会返回有效路径.除此之外,我想创建一种更好的方法来确保在查找类型之前将 B 模块加载到内存中.

This code actually does not work as the Path.GetDirectoryName function does not return a valid path. Apart from this I would like to create a better way t ensure that B module is loaded in memory before looking for its type.

有什么建议吗?

推荐答案

简单的 Assembly.Load 不起作用?您不必知道位置,只需知道名称.

The simple Assembly.Load does not work? You don't have to know the location, only the name.

在相同情况下,我使用 Assembly.CodeBase ,并且效果很好:

I use Assembly.CodeBase in the same situation and it works fine:

string codebase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
Uri p = new Uri(codebase);
string localPath = p.LocalPath;
var myassembly = System.Reflection.Assembly.LoadFrom(System.IO.Path.Combine(localPath, "MyAssebmly.dll"));

最诚挚的问候,彼得

这篇关于动态加载库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆