0

我已经PartCreationPolicy.NonShared为我的观点设置了,但是对于某些特定的用户我可以使用CreationPolicy.Shared(为了提高性能),我不确定它是否可以完成。正如我ServiceLocator用来获取视图实例一样。喜欢

view = ServiceLocator.GetInstance<MyUserControl>("view_contract");

什么可能是最好的解决方案。我在谷歌上搜索过,我找到了一些解决方案CompositionContainer.GetExports,但是

1- 我无法CompositionContainer在我的 ViewModel 中获取实例。

2-在这篇文章中,它写在GetExport

导出的 Value 的连续调用将返回相同的实例,无论该部分是否具有共享或非共享生命周期。

请任何人建议最好的解决方案和一些示例代码片段吗?

4

1 回答 1

2

据我了解,您有一些“业务逻辑”来区分共享视图和非共享视图(例如,取决于用户的类型)。我认为这不应该在您的 DI 容器中处理...

如果您想通过“prism-style”实现这一点,那么您可以INavigationAware在 ViewModel 中使用 prism 界面:视图和 viewModel 是非共享的,您可以通过导航激活/构建它(与 MEF 完美配合)。将“共享”/“非共享”的业务逻辑放入“IsNavigationTarget”方法中。Prism 将自动调用此方法并仅在需要时创建新的视图实例。

这是一些代码:

视图(不要忘记视图名称作为导航目标!):

[Export(Constants.ViewNames.MyFirstViewName)] // The Export Name is only needed for Prism's view navigation.
[PartCreationPolicy(CreationPolicy.NonShared)] // there may be multiple instances of the view => NO singleton!!
public partial class MyFirstView
{ ... }

视图模型:

    [PartCreationPolicy(CreationPolicy.NonShared)] 
    [Export]
    public class MyFirstViewModel: Microsoft.Practices.Prism.Regions.INavigationAware
    {
       #region IINavigationAware
        // this interface ships with Prism4 and is used here because there may be multiple instances of the view
        // and all this instances can be targets of navigation.

        /// <summary>
        /// Called when [navigated to].
        /// </summary>
        /// <param name="navigationContext">The navigation context.</param>
        public override void OnNavigatedTo(NavigationContext navigationContext)
        {                    
            ...
        }

        /// <summary>        
        /// </summary>
        public override void OnActivate()
        {
            ...
        }

        /// <summary>
        /// Determines whether [is navigation target] [the specified navigation context].
        /// </summary>
        /// <param name="navigationContext">The navigation context.</param>
        /// <returns>
        ///     <c>true</c> if [is navigation target] [the specified navigation context]; otherwise, <c>false</c>.
        /// </returns>
        public override bool IsNavigationTarget(NavigationContext navigationContext)
        {
            // use any kind of busines logic to find out if you need a new view instance or the existing one. You can also find any specific target view using the navigationContext...
            bool thereCanBeOnlyOneInstance = ...
            return thereCanBeOnlyOneInstance;
        }    

        #endregion
}
于 2013-02-20T12:50:40.600 回答