【发布时间】:2013-02-25 22:10:03
【问题描述】:
谁能解释一下我发生了什么事?我有一个测试项目来测试我的服务的虚拟实例。在测试项目中,我简单引用了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 堆栈跟踪: 在 Export.CaseOutputProcess.CaseOutputGeneratorFactory.GetCaseOutputGeneratorObject(String assemblyName, String className) 在 C:\Monitor\Export.CaseOutputProcess\CaseOutputGeneratorFactory.cs:56 行 在 Monitor.BOMock.GenerateCaseOutput(字符串 OutputFolder,字符串 iFile,Int32 seqNum,DataTable CaseSettings,字符串 SettingFileName) 在 C:\Monitor\BOMock\BOMock.cs:1069 行 在 C:\Monitor\BOMock\BOMock.cs:line 492 InnerException 中的 Monitor.BOMock.Handling():
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。请问我该如何解决或解决这个问题?提前致谢。
【问题讨论】:
-
您是否研究过 Ninject 的依赖注入?
-
full 消息是什么?当您在两个不同的程序集中声明
ICaseOutputGenerator时,通常会发生 - 在这种情况下,这是两个不同且不相关的ICaseOutputGenerator接口。 -
这恰好是完整的消息。我不确定我应该在此发布哪些其他信息。请让我知道您究竟需要我发布什么。
-
CaseOutputGenerator是否实现了ICaseOutputGenerator接口? -
是的,它确实实现了它。
标签: c# .net visual-studio-2010 reflection