据我了解,您有一些“业务逻辑”来区分共享视图和非共享视图(例如,取决于用户的类型)。我认为这不应该在您的 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
}