我正在创建一个自定义 powershell 1.0 cmdlet,它允许我将 powershell 脚本中的异常提供给 Microsoft Enterprise Library v5.0 异常处理块。
我从外部文件加载我的异常处理配置,因为 cmdlet 被编译成 dll,然后尝试使用配置创建 ExceptionManager 的实例。
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource config =
new Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource(configFile);
WriteDebug("Config loaded from " + Path.GetFullPath(configFile));
EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(config);
exManager = EnterpriseLibraryContainer.CreateDefaultContainer(config).GetInstance<ExceptionManager>();
当我从 powershell 调用我的命令并出现以下错误时,这将失败:
Microsoft.Practices.ServiceLocation.ActivationException:尝试获取 ExceptionManager 类型的实例时发生激活错误,键“”---> Microsoft.Practices.Unity.ResolutionFailedException:依赖项解析失败,类型 =“Microsoft.Practices.EnterpriseLibrary。 ExceptionHandling.ExceptionManager”,名称 = “(无)”。异常发生时:解决时。异常是: InvalidOperationException - 无法构造类型 ExceptionManager。您必须配置容器以提供此值。
令人沮丧的是,当在具有完全相同配置的独立控制台应用程序中使用代码时,代码工作得非常好。我不太确定为什么会出现此错误;我确保我使用的是配置文件中引用的相同程序集,并且我确保我在我的项目中引用了所有必要的企业库 dll。
此外,我必须将企业库 dll 复制到 powershell 安装目录 (%SystemRoot%\system32\WindowsPowerShell\v1.0),否则我会收到 FileNotFoundExceptions 提示在配置文件时无法找到正确的库正在处理。我对 powershell 或企业库没有太多经验,但我猜这可以通过使用 AppDomain 设置来解决。