1

我试图在WPF MVVM应用程序中实现Unity,但我错过了大图。Caliburn.Micro + Unity 2.1 + MVVM:示例代码

在这个时刻我已经创建了一个引导程序是这样的:

public class MainBootstrapper : Bootstrapper<MainViewModel> 
    { 
    private UnityContainer container; 

    protected override void Configure() 
    { 
     container = new UnityContainer(); 
     container.RegisterType<IServiceLocator, UnityServiceLocator>(new ContainerControlledLifetimeManager()); 
     container.RegisterType<IWindowManager, WindowManager>(new ContainerControlledLifetimeManager()); 
     container.RegisterType<IEventAggregator, EventAggregator>(new ContainerControlledLifetimeManager()); 
    } 

    protected override object GetInstance(Type service, string key) 
    { 
     if (service != null) 
     { 
     return container.Resolve(service); 
     } 

     if (!string.IsNullOrWhiteSpace(key)) 
     { 
     return container.Resolve(Type.GetType(key)); 
     } 

     return null; 
    } 

    protected override IEnumerable<object> GetAllInstances(Type service) 
    { 
     return container.ResolveAll(service); 
    } 

    protected override void BuildUp(object instance) 
    { 
     container.BuildUp(instance); 
    } 
    } 

怎么样呢就是用最好的方法? 此代码当前工作:

public class MainViewModel : PropertyChangedBase 
    { 
    public MainViewModel() 
    { } 

    [Dependency] 
    public Sub1ViewModel Sub1VM { get; set; } 
    [Dependency] 
    public Sub2ViewModel Sub2VM { get; set; } 
    } 

中的MainView有这样的:

<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="*" /> 
     <RowDefinition Height="*" /> 
    </Grid.RowDefinitions> 

    <ContentControl Grid.Row="0" Name="Sub1VM" /> 
    <ContentControl Grid.Row="1" Name="Sub2VM" /> 

</Grid> 

首先:我共享的代码,这是使用Unity +卡利的正确方法是什么?

现在让我们说我的Sub1VM使用模型'M1',但是Sub2VM需要使用相同的模型来显示信息,而不是通过创建另一个模型M1的实例。 (singleton)

这是如何工作的?显示我在每个viewmodel构造函数中使用IServiceLocator?有人可以分享一个代码示例来解释它吗?

回答

1

首先我McDonnellDean同意,你应该了解的屏幕,指挥及作曲的文章(如果我是你,我会读之前所有的文章太了解Caliburn.Micro如何工作的。)。除此之外,您正确实施了Unity,您可以检查Unity as IoC Container for Caliburn.Micro了解更多信息。另一方面,这里混合了两个概念,即依赖注入和MVVM。关于你关于模型的问题,我还会更喜欢构造函数注入,如果你想要一个模型的实例,也许你可以注入一个Factory为你创建这个模型,并将它包装到两个不同的视图模型中,并通过两个不同的属性。最后我真的鼓励你们阅读的教程(start here),至少是基本的话题。

+0

感谢您的“从这里开始”链接 – juFo

+0

@juFo,不客气。 –

1

我不太了解Unity,但您的配置看起来正确。

至于你的注射点。我会说,而不是做属性注入,你应该做建设者注入。你在做什么很好,但是你可能想要查看屏幕和导体,这些可以让你为ViewModels添加生命周期。通常,它应该是这样的:

  • 引导程序打开ShellViewModel

  • ShellViewModel通过构造函数注入发生在MainViewModel作为IConductorOneActive

  • MainViewModel需要IScreens的集合。

  • ShellViewModel调用MainViewModel在MainViewModel上激活方法。

请参阅Screens, Conductors and Composition。正如我上面所说的,你的方式很好,但在手动方面有一点点,意味着你必须手工连接所有东西。