1

我一直在努力寻找理想的方法。现在,我在创建应用程序 shell 之前在 Boostrapper 中创建了我的服务,方法是:

protected override DependencyObject CreateShell() 

创建外壳后,我创建所有视图模型,传递他们需要的服务。

所以首先,我想知道这是否是一个好习惯。另外,我尝试在 .config 文件中找到声明服务的示例,但我真的没有看到任何示例。这也不是一个好习惯吗?

例子:

    protected override DependencyObject CreateShell()
    {
        appWnd = ServiceLocator.Current.GetInstance<ApplicationWindow>();
        Container.RegisterInstance<ILicensing>(new LicensingService());
        Container.RegisterInstance<IAnotherService>(new AnotherService());

        return appWnd;
    }
4

1 回答 1

1

UnityBootstrapper 的方法 ConfigureContainer() 应该被覆盖以执行您的要求:

MSDN - 配置容器:

复合应用程序库和在它之上构建的应用程序都依赖于一个容器来注入所需的依赖项。在容器配置阶段,注册了几个核心服务,如 UnityBootstrapper 中的以下代码所示。

UnityBootstrapper 上的 MSDN

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() 方法不是执行此操作的地方,因为您应该在此处创建外壳。

因此,简而言之,只需覆盖 ConfigureCatalog() 并将您的代码粘贴到那里。

于 2013-03-05T19:23:26.710 回答