我一直在努力解决这个问题的理想方法。现在,我在创建应用程序shell之前在Boostrapper中创建了我的服务,方法是:
protected override DependencyObject CreateShell()
创建shell之后,我创建了所有视图模型,并传递了所需的服务。
首先,我想知道这是不是一个好习惯。此外,我试图找到在.config文件中声明服务的示例,但我真的没有看到任何。这不是一个好习惯吗?
示例:
protected override DependencyObject CreateShell()
{
appWnd = ServiceLocator.Current.GetInstance<ApplicationWindow>();
Container.RegisterInstance<ILicensing>(new LicensingService());
Container.RegisterInstance<IAnotherService>(new AnotherService());
return appWnd;
}
答案 0 :(得分:1)
UnityBootstrapper的方法ConfigureContainer()应该被覆盖以满足您的要求:
MSDN - ConfigureContainer:
复合应用程序库和构建的应用程序 它的顶部依赖于一个容器来注入所需的依赖项。 在容器配置阶段,有几个核心服务 已注册,如UnityBootstrapper的以下代码所示。
MSDN示例:
protected virtual void ConfigureContainer()
{
…
if (useDefaultConfiguration)
{
RegisterTypeIfMissing(typeof(IServiceLocator), typeof(UnityServiceLocatorAdapter), true);
RegisterTypeIfMissing(typeof(IModuleInitializer), typeof(ModuleInitializer), true);
RegisterTypeIfMissing(typeof(IModuleManager), typeof(ModuleManager), true);
RegisterTypeIfMissing(typeof(RegionAdapterMappings), typeof(RegionAdapterMappings), true);
RegisterTypeIfMissing(typeof(IRegionManager), typeof(RegionManager), true);
RegisterTypeIfMissing(typeof(IEventAggregator), typeof(EventAggregator), true);
RegisterTypeIfMissing(typeof(IRegionViewRegistry), typeof(RegionViewRegistry), true);
RegisterTypeIfMissing(typeof(IRegionBehaviorFactory), typeof(RegionBehaviorFactory), true);
}
}
您也可以直接使用Container
在此处注册实例,就像您已经做的那样。
CreateShell()方法不是这样做的地方,因为你只需要在这里创建shell。
因此,简而言之,只需覆盖ConfigureCatalog()并将代码粘贴到那里。