我正在尝试使用反射为.NET 完成(似乎是)一个极其简单的依赖注入机制。目标是为 ServiceFactory 类提供接口,并使用反射来确定该接口的可用实现者,并根据 App.config 部分选择实现。听起来很简单。
我选择的路线是使用每个服务实现项目的构建后事件将实现 .dll 复制到“ServiceImplementations”文件夹中。然后,ServiceFactory 类在此文件夹中查找可用的、有效的接口实现者。这个想法是,使用反射,我应该能够在运行时纯粹在反射中加载这个任意 DLL 及其所有依赖项。这是我希望达到的目标。
在这个过程中的某个地方,我很好地加载了这些依赖项。我可以使用 var asmDomainAssemblies = AppDomain.CurrentDomain.GetAssemblies() 检查我当前加载的程序集
因此,我继续进行反射爬网,最终加载了依赖程序集(在本例中为 EntityFramework,通过 NuGet 加载,以及 System.Web.ApplicationServices,一个系统文件)。一切都很好。直到我到达这行代码:
var serviceImplementationAssembly = CheckLoadedAssemblies(assemblyName); // This function loads the service implementation assembly and its dependencies
var appDomainAsm = AppDomain.CurrentDomain.GetAssemblies();
var implementationTypes = serviceImplementationNamespace.GetTypes(); // Exception here
在最后一行代码中,抛出了 ReflectionTypeLoadException。此异常包含两个 LoaderExceptions(每个都是 FileNotFoundException),并带有以下消息:
Could not load file or assembly 'EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified.":"EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
这很奇怪。如果我检查上面的 asmDomainAsm 变量,我可以看到该确切的程序集签名已加载到我当前的 AppDomain 中。我不明白为什么 Reflection 不能识别这些是相同的程序集,即使我在不同时间加载它们。
提前谢谢你的帮助。