C# : Type. GetType 在动态加载程序集的类上为 null

标签 c# types .net-assembly appdomain gettype

这是我关于堆栈溢出的第一个问题。我试图寻找解决方案,但在任何地方都找不到一个或类似的解决方案。

我有一个 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/

相关文章:

hibernate - JPA 实体 ID - long 或 Long

c# - 将 C 中的外部 DLL 附加到 c# 中的 WinForm 项目

C# 将不同版本的程序集加载到同一个项目

c# - 使用 NInject,在注入(inject)构造函数参数时解析 IEnumerable<T> 失败,但在执行 Get<IEnumerable<T>>() 时则不会

delphi - 什么是托管类型?它们是特定于 Delphi 的吗?它们是特定于 Windows 的吗?

c# - 如何将选定的微调器项目获取到字符串?

go - dynamodbattribute.UnmarshalMap 将我的变量类型更改为 map[string]interface{}

asp.net - 在内联 vb 代码中引用类库

c# - 格式字符串中的多个前导 '#' 符号有什么作用吗?

c# - 应用程序不加载azure应用程序配置功能标志值,但加载配置值