使用 Prism 和 Unity 容器时出现激活错误
本文关键字:激活 错误 Prism Unity 使用 | 更新日期: 2023-09-27 18:36:05
我有以下控制台程序,我尝试在其中应用 SOLID 原则、Unity 和 Prism 6 模块化的依赖注入:
主程序:
UnityContainer container = new UnityContainer();
container.RegisterInstance<IServiceLocator>(new UnityServiceLocator(container));
container.RegisterType<IModuleInitializer, ModuleInitializer>();
TextLogger logger = new TextLogger();
container.RegisterInstance<ILoggerFacade>(logger);
ConfigurationModuleCatalog catalog = new ConfigurationModuleCatalog();
container.RegisterInstance<IModuleCatalog>(catalog);
container.RegisterType<IModuleManager, ModuleManager>();
IModuleManager manager = container.Resolve<IModuleManager>();
manager.Run();
应用配置文件:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="modules" type="Prism.Modularity.ModulesConfigurationSection, Prism.Wpf" />
</configSections>
<modules>
<module assemblyFile="CalcCommandParsingLib.dll" moduleType="CalcCommandParsingLib.CalculatorCommandParsingModule, CalcCommandParsingLib, Version=1.0.0.0, Culture = neutral, PublicKeyToken=null" moduleName="Parsing" />
<module assemblyFile="CalculatorLibrary.dll" moduleType="CalculatorLibrary.CalculatorModule, CalculatorLibrary, Version=1.0.0.0, Culture = neutral, PublicKeyToken=null" moduleName="Calculator" />
<module assemblyFile="InputOutputLibrary.dll" moduleType="InputOutputLibrary.InputOutputModule, InputOutputLibrary, Version=1.0.0.0, Culture = neutral, PublicKeyToken=null" moduleName="InputOutput" />
<module assemblyFile="MainModuleLibrary.dll" moduleType="MainModuleLibrary.MainModule, MainModuleLibrary, Version=1.0.0.0, Culture = neutral, PublicKeyToken=null" moduleName="Main" >
<dependencies>
<dependency moduleName="Calculator" />
<dependency moduleName="Parsing" />
<dependency moduleName="InputOutput" />
</dependencies>
</module>
</modules>
</configuration>
以及导致错误的四个模块之一:
public class MainModule : IModule
{
IServiceLocator serviceLocator;
public MainModule(IServiceLocator serviceLocator)
{
this.serviceLocator = serviceLocator;
}
public void Initialize()
{
ICalculatorReplLoop loop = serviceLocator.GetInstance<ICalculatorReplLoop>();
loop.Run();
}
}
错误发生在以下行:
ICalculatorReplLoop loop = serviceLocator.GetInstance<ICalculatorReplLoop>();
它是:
类型的异常 "Microsoft.Practices.ServiceLocation.ActivationException" 发生在 Microsoft.实践.服务位置.dll但未在用户中处理 法典
其他信息:尝试获取时发生激活错误 ICalculatorReplLoop 类型的实例,键 "
有人可以帮我吗?
我认为至少有两件事需要改变:
-
您还应该注册 ICalculatorReplLoop
container.RegisterType<ICalculatorReplLoop, CalculatorReplLoop>();
-
对我来说,直接注入所需的接口,然后通过服务定位器解决它会更有意义,因此:
public MainModule(ICalculatorReplLoop calc) { this.calc= calc; }