如何使用PRISM 4.1& amp;统一?

时间:2013-12-05 11:40:51

标签: wpf silverlight mvvm unity-container prism-4

我正在使用PRISM 4.1&amp ;;编写WPF应用程序。统一。该应用程序将配置每个UI组件,包括Shell本身!

E.g。我有一个名为IShell的界面。如果应用程序的消费者对我的默认实现不满意,则可以拥有自己的IShell实现,这些实现具有以某种固定方式定义的区域和视图。

现在从我的Bootstrapper类(继承UnityBootstrapper)开始,我想知道使用Unity容器为IShell注册的类型。覆盖CreateShell将返回IShell的配置类型。

我的App.config看起来像这样:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity>
    <container>
        <register type="Interfaces.IShell, Interfaces" mapTo="PrismApp.Shell, PrismApp"/>
    </container>
  </unity>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

在Bootstrapper类中,我有以下代码:

public class PrismAppBootstrapper : UnityBootstrapper
{
    protected override DependencyObject CreateShell()
    {
        var obj =  ServiceLocator.Current.GetInstance<IShell>() as DependencyObject;
        return obj;
    }
}

在WPF应用程序的App.xaml.cs中,我正在实例化PrismAppBootstrapper

 PrismAppBootstrapper prismAppBootstrapper = new PrismAppBootstrapper();
        prismAppBootstrapper.Run();

但是,当我运行此代码时,我得到了异常:“ InvalidOperationException - 当前类型Interfaces.IShell是一个接口,无法构造。是否缺少类型映射?

如何解决这个问题? 为什么应用程序无法知道app.config文件中存在的IShell的注册类型?

2 个答案:

答案 0 :(得分:0)

使用Unity容器可以保持Shell的可配置性。

问题是我的Unity Container未正确配置为从app.config文件中读取映射/注册。因此,它无法在运行时知道IShell的映射。

我必须在我的CreateShell课程中覆盖其他方法以及PrismAppBootstrapper

E.g。

public class PrismAppBootstrapper : UnityBootstrapper
    {
        protected override IModuleCatalog CreateModuleCatalog()
        {
            ModuleCatalog catalog = new ConfigurationModuleCatalog();
            return catalog;
        }

        protected override void ConfigureContainer()
        {
            base.ConfigureContainer();
            UnityConfigurationSection configurationSection =
                (UnityConfigurationSection) ConfigurationManager.GetSection("unity");
            if (configurationSection != null)
            {
                configurationSection.Configure(this.Container);
            }
        }

        protected override DependencyObject CreateShell()
        {
            IShell shell = this.Container.TryResolve<IShell>();
            return shell as Window;
        }

        protected override void InitializeShell()
        {
            base.InitializeShell();

            Application.Current.MainWindow = (Window)this.Shell;
            Application.Current.MainWindow.Show();
        }
    }

答案 1 :(得分:-1)

您是否应该使用UnityBootstrapper容器来解析shell?

var obj =  Container.Resolve<IShell>() as DependencyObject;
return obj;