我有以下项目结构:
Web API
- 类库
A
- 类库
B
- 类库
C
这些是项目之间的参考
-
Web API
直接引用A
and B
-
B
直接引用C
C
有一个方法需要确保A
被加载以通过反射使用其中定义的类型。
我的代码实际上如下
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
模块在查找其类型之前加载到内存中。
有什么建议吗?
简单的Assembly.Load
不起作用?您不必知道位置,只需知道名称即可。
I use Assembly.CodeBase
在同样的情况下,它工作得很好:
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"));
此致,
彼得
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)