这是我关于堆栈溢出的第一个问题。我试图寻找解决方案,但在任何地方都找不到一个或类似的解决方案。
我有一个 MVC 网站项目,它具有不同的 DLL(插件),并且由于这些 DLL 不需要部署在所有环境中,所以我从文件夹中的 Global.asax 中的 Application_Start 上动态加载它们,并仅部署我需要的内容每个环境的需要。所以我不知道在项目中引用它们,这样我就可以为所有人构建一个版本。
我的问题是 Type.GetType("FullClassName, AssemblyName") 总是在这些插件中的对象上返回 null。
在Application_Start上,我基本上加载一个程序集,将其注册到GAC,将其加载到当前的AppDomain中,初始化其元数据并使用反射运行其 Bootstrap ,以在全局Unity容器中注册组件。
foreach (string file in fileList) {
string fileName = (Path.GetFileName(file));
Assembly asm = Assembly.LoadFrom(file);
foreach (Type assemblyType in asm.GetTypes()) {
new System.EnterpriseServices.Internal.Publish().GacInstall(file);
AppDomain.CurrentDomain.Load(asm.GetName());
MetaDataHelper.InitialiseMetadataForAssembly(asm);
IBootstrapper bootsrapper = (IBootstrapper)Activator.CreateInstance(assemblyType, container);
bootsrapper.Initialise();
}
}
我也尝试过这种方法,对我的程序集进行强命名并将它们添加到 web.config 中,但没有效果。
<dependentAssembly>
<assemblyIdentity name="MyAssembly" culture="neutral" publicKeyToken="123456789"/>
<codeBase version="1.0.1524.23149" href="FILE://C:/Myassemblies/MyAssembly2.dll"/>
</dependentAssembly>
有人可以帮我吗,我错过了什么吗?
提前致谢。
最佳答案
我明白了。我简直不敢相信这个解决方案是如此简单。经过对 AppDomain.CurrentDomain 和一些 MSDN 文档的一些探索后,我只需要实现一个自定义程序集解析事件处理程序并将其添加到当前域。
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(currentDomain_AssemblyResolve);
static Assembly currentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
--args.Name is the assembly name passed to the GetType("FullClassName,AssemblyName");
--Search in LoadedAssemblies by name and return it.
}
关于C# : Type. GetType 在动态加载程序集的类上为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50624051/