我有以下控制台程序,其中我尝试应用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();
App配置文件:
<?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.Practices.ServiceLocation.dll但未在用户中处理 代码
其他信息:尝试获取时发生激活错误 ICalculatorReplLoop类型的实例,键“”
有人可以帮帮我吗?
答案 0 :(得分:0)
我认为至少有两件事需要改变:
您还应该注册ICalculatorReplLoop
container.RegisterType<ICalculatorReplLoop, CalculatorReplLoop>();
我更有意义的是直接注入所需的接口,然后通过serviceLocator解决它:
public MainModule(ICalculatorReplLoop calc)
{
this.calc= calc;
}