【问题标题】:Prism-WPF equivalent to Silverlight's: CompositionInitializer class and SatisfyImports()Prism-WPF 等效于 Silverlight 的:CompositionInitializer 类和 SatisfyImports()
【发布时间】:2013-01-27 08:34:14
【问题描述】:

我正在使用 Prism-MEF-WPF,有时我需要从 XAML 构建视图模型 视图的,所以不涉及容器,不能做依赖注入 自动(因为没有与 VM 一起使用的导出属性)。所以应该有一些 Prism-WPF 中的类,例如 CompositionInitializer,使我能够要求容器 进行注入。如果有等效的类如何使用它,如果有 知道我使用 MEF,没有等效的如何从视图的 xaml 构造视图模型。 提前致谢。

【问题讨论】:

    标签: wpf prism mef


    【解决方案1】:

    问题是,如果没有无参数构造函数,您就无法在 XAML 中创建对象。

    使用 ServiceLocator,您可以实现这一点。它将作为 IoC 工作(由 Prism/MEF 设置,您只需删除 .dll):

    xaml:

    <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>
    

    代码隐藏:

    class ViewModel : NotificationObject
    {
        public ViewModel()
        {
            var firstDependency = ServiceLocator.Current.GetInstance<FirstDependencyType>();
            //... more dependencies here instead of as constructor parameters
        }
    
        //class code omitted for brievity
    }
    

    【讨论】:

      【解决方案2】:

      这是我从 Agustin Adami "http://blogs.southworks.net/aadami" 那里得到的正确答案:

      根据我的理解,仅当视图模型没有任何构造函数参数时,才能在 XAML 中将视图模型实例化为视图的 DataContext。据我所知,目前不支持通过与逆控制容器合作创建在 XAML 中定义的对象。

      关于 CompositionInitializer 类,据我所知 WPF 没有等效类,另一方面,关于这个主题,我相信您会发现以下博客文章很有趣:

      •http://reedcopsey.com/2010/03/26/mef-compositioninitializer-for-wpf/ 另外,我相信另一种方法可能是注册 CompositionContainer 类,就像这个线程中提到的那样:

      http://compositewpf.codeplex.com/discussions/311933 因为这可以让您在视图模型的构造函数中检索此类,以便调用 SatisfyImportsOnce 方法以满足传递的类中定义的 Imports:

      this.compositionContainer =ServiceLocator.Current.GetInstance(); this.compositionContainer.SatisfyImportsOnce(this);

      【讨论】:

        【解决方案3】:

        Bootstrapper 类是您正在寻找的。它使用UnityContainer 来注入依赖项。这个链接here 可能你也感兴趣..

        编辑

        如果我说对了,你想从你的 xaml 创建一个 ViewModel,可以这样实现(这里本地是你的 ViewModel 类的命名空间)-

        <Window.DataContext>
            <local:ViewModel/>
        </Window.DataContext>
        

        【讨论】:

        • 首先我使用的是 MEF(托管扩展框架)而不是 Unity,其次重点不是依赖注入,重点是通过视图的 xaml 创建 VM。
        • 感谢您的关心。我已发送正确答案,您可以查看。
        猜你喜欢
        • 1970-01-01
        • 2011-03-23
        • 1970-01-01
        • 2011-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-25
        • 1970-01-01
        相关资源
        最近更新 更多