无法将XXXXXX类型的对象强制转换为IXXXXX类型(.NET 4.0)

有人可以解释一下我发生了什么事吗? 我有一个测试项目,测试我的服务的虚拟实例。 在测试项目中,我只是引用了dummyService.exe和System.SystemProcess dll。

然而,在我的dummyService项目中,我引用了类库,它本身使用来自其他组件的其他dll以及我的解决方案中的其他项目。

问题是,当我运行我的测试时,会抛出exception(加载并在dummyService中工作的dll的First Chanceexception),此外还有invalidcastexception(下面的错误消息)。

无法将“Export.CaseOutputGenerator”类型的对象强制转换为“Export.ICaseOutputGenerator”。 捕获到System.InvalidCastException Message =无法将类型为“Export.CaseOutputProcess.CustomCaseOutputGenerator”的对象强制转换为类型“Export.CaseOutputProcess.ICaseOutputGenerator”。 Source = Export.CaseOutputProcess StackTrace:位于C:\ Monitor \ Export.CaseOutputProcess \ CaseOutputGeneratoryFactory.cs中的Export.CaseOutputProcess.CaseOutputGeneratoryFactory.GetCaseOutputGeneratorObject(String assemblyName,String className):Monitor.BOMock.GenerateCaseOutput中的第56行(String OutputFolder,String iFile C:\ Monitor \ BOMock \ BOMock.cs中的,Int32 seqNum,DataTable CaseSettings,String SettingFileName):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恰好是要创建实例的类的名称。

在代码中,如您所见,使用reflection我在assemblyName PATH提供的(String assemblyName) http://msdn.microsoft.com/en-us/library/system.reflection.assembly.loadfrom.aspx上加载程序集,并且然后再次使用reflection,然后我创建一个包含在加载的程序集中的className(String className)的实例。 http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

我该如何解决这个问题? 我不想在测试项目中引用我的所有dll。 我该如何解决或解决这个问题? 提前致谢。

基于该堆栈跟踪,它看起来像找不到类型所在的程序集。 如果您只是添加对已编译的exe的引用,那么您可能不会随其他库获取它。 我想你有几个选择:

  1. 继续并咬紧牙关:添加对测试项目中其他库的引用。 它们通常不具有传递性:只是因为您的服务知道它们并不一定意味着您的测试程序集也知道它们。
  2. 在测试项目中添加一个后编译步骤,复制其他程序集,以便运行测试的应用程序域找到它们。
  3. 使用dependency injection和控制容器的反转。 那里有很多,但想到Castle Windsor,StructureMap和Unity。 斯科特汉塞尔曼在他的博客上有一个很好的列表: http : //www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx