排查Unity IoC容器异常:给定的程序集名称或代码库无效
我之前也碰到过一模一样的问题,这个0x80131047错误确实很让人头疼——外层异常信息太笼统,根本看不出到底哪出问题。别着急,咱们一步步来揪出搞鬼的那个类型:
第一步:深挖异常的内层细节
你现在只打印了外层异常,很多时候真正的根源藏在InnerException里。修改你的捕获代码,把所有嵌套的异常信息都打出来:
catch (Exception ex) { var currentException = ex; int exceptionLevel = 0; while (currentException != null) { Console.WriteLine($"=== 异常层级 {exceptionLevel} ==="); Console.WriteLine($"错误信息: {currentException.Message}"); Console.WriteLine($"调用栈:\n{currentException.StackTrace}\n"); currentException = currentException.InnerException; exceptionLevel++; } }
运行后,你大概率会在某个内层异常里看到具体的类型或程序集名称,比如“无法加载程序集XXX”或者“找不到类型XXX, XXXAssembly”,这直接就能定位问题。
第二步:检查Unity配置文件的拼写和格式
打开你的App.config/Web.config,找到<unity>节点下的配置:
- 检查每个
<type>节点的type属性,格式必须是完整类型名, 程序集名,注意程序集名不能带.dll后缀(比如应该写MyApp.UserService, MyApp.Services而不是MyApp.UserService, MyApp.Services.dll)。 - 核对程序集名称的拼写,有没有大小写错误或者少打了字符。
- 确认配置里的所有类型都确实存在于对应的程序集中。
第三步:用Unity的诊断扩展追踪加载过程
Unity自带的Diagnostic扩展可以输出配置过程的详细日志,能看到它尝试加载哪个类型时失败了。先添加这个扩展再执行配置:
_container = new UnityContainer(); // 添加诊断扩展,开启详细日志 _container.AddExtension(new Diagnostic()); var unityConfigurationSection = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); if (unityConfigurationSection != null) { try { unityConfigurationSection.Configure(_container); } catch (Exception ex) { // 用刚才的方式打印所有异常细节 var currentException = ex; int exceptionLevel = 0; while (currentException != null) { Console.WriteLine($"=== 异常层级 {exceptionLevel} ==="); Console.WriteLine($"错误信息: {currentException.Message}"); Console.WriteLine($"调用栈:\n{currentException.StackTrace}\n"); currentException = currentException.InnerException; exceptionLevel++; } } }
运行后控制台会输出大量日志,搜索“Error”或者“Failed”关键词,就能找到加载失败的那个类型。
第四步:手动验证类型加载
如果上面的方法还是没找到,你可以把配置文件里的每个类型单独拿出来,用Type.GetType()手动测试加载:
// 替换成你配置里的类型名和程序集名 var testType = Type.GetType("MyApp.UserService, MyApp.Services"); if (testType == null) { Console.WriteLine("找不到这个类型!"); }
如果这个调用返回null或者抛出异常,那就是这个类型/程序集的问题,逐个排查配置里的所有类型就能找到根源。
最后检查程序集是否存在
确认配置中提到的所有程序集都在你的应用输出目录(比如bin/Debug或者bin/Release)里,没有缺失、版本不匹配或者被覆盖的情况。
附你的原始代码片段:
_container = new UnityContainer(); var unityConfigurationSection = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); if (unityConfigurationSection != null) { try { unityConfigurationSection.Configure(_container); } catch (Exception ex) { Console.WriteLine(ex); } }
异常信息:
The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
内容的提问来源于stack exchange,提问作者Christofer Ohlsson

