有人可以解释发生在我身上的事情吗?我有一个测试项目来测试我的服务的虚拟实例。在测试项目中,我只是简单地引用了 dummyService.exe 和 System.SystemProcess dll。
然而,在我的 dummyService 项目中,我引用了类库,它本身使用来自其他组件的其他 dll 以及我的解决方案中的其他项目。
问题是,当我运行测试时,会抛出异常(在 dummyService 中加载和工作的 dll 的第一次机会异常),此外还有 invalidcast 异常(下面的错误消息)。
无法将“Export.CaseOutputGenerator”类型的对象转换为“Export.ICaseOutputGenerator”类型。捕获 System.InvalidCastException 消息=无法将类型为“Export.CaseOutputProcess.CustomCaseOutputGenerator”的对象转换为类型“Export.CaseOutputProcess.ICaseOutputGenerator”。Source=Export.CaseOutputProcess StackTrace: 在 Export.CaseOutputProcess.CaseOutputGeneratorFactory.GetCaseOutputGeneratorObject(String assemblyName, String className) 在 C:\Monitor\Export.CaseOutputProcess\CaseOutputGeneratoryFactory.cs: 第 56 行在 Monitor.BOMock.GenerateCaseOutput(String OutputFolder, String iFile , Int32 seqNum, DataTable CaseSettings, String SettingFileName) in C:\Monitor\BOMock\BOMock.cs: C:\Monitor\BOMock\BOMock.cs 中 Monitor.BOMock.Handling() 中的第 1069 行:第 492 行 InnerException:
public static ICaseOutputGenerator GetCaseOutputGeneratorObject(string assemblyName, string className)
{
ICaseOutputGenerator customeOutputGen = null;
var obj = GetObject(assemblyName, className);
if (obj != null)
caseOutputGen = (ICaseOutputGenerator)obj; // FAILS HERE
return caseOutputGen;
}
private static object GetObject(string fullName, string className)
{
try
{
Type caseOutputGen = null;
var localAssembly = Assembly.LoadFrom(fullName);
foreach (var testType in localAssembly.GetTypes())
{
if (!testType.FullName.EndsWith(className, StringComparison.InvariantCultureIgnoreCase)) continue;
caseOutputGen = testType;
break;
}
if (caseOutputGen == null) return null;
var obj = Activator.CreateInstance(caseOutputGen);
return obj;
}
catch (FileNotFoundException ex)
{
throw new Exception("Failed to load assembly: " + Environment.NewLine + fullName, ex);
}
catch (Exception ex)
{
throw new Exception("Failed to load assembly: " + Environment.NewLine + fullName, ex);
}
}
其中 assemblyName 是要加载的 dll 文件的路径,而 className 恰好是要创建实例的类的名称。
如您所见,在代码中,我使用反射在提供的 assemblyName PATH 加载程序集(String assemblyName)http://msdn.microsoft.com/en-us/library/system.reflection.assembly.loadfrom.aspx,并且然后再次使用反射,然后创建一个包含在加载程序集中的类名(字符串类名)的实例。http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
请问我该如何解决这个问题?我不想在测试项目中引用我所有的 dll。请问我该如何解决或解决这个问题?提前致谢。