我的项目结构如下:
Web APIABC这些是项目之间的参考资料。
Web API直接引用A和BB直接引用CC有一个方法,它需要确保加载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模块类型之前将其加载到内存中。
有什么建议吗?
发布于 2016-02-28 12:23:54
简单的Assembly.Load不工作吗?你不需要知道地点,只知道名字。
我在相同的情况下使用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"));向你问好,彼得
发布于 2018-06-20 11:53:04
修改Peter的答案,但逻辑更正确,因为他的组合将失败,没有理由创建URL来获取本地文件路径。
using System.Reflection;
using System.IO;
var appDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var myAssembly = Assembly.LoadFrom(Path.Combine(appDir, "MyAssebmly.dll"));https://stackoverflow.com/questions/35682347
复制相似问题