我试图在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?有人可以分享一个代码示例来解释它吗?
感谢您的“从这里开始”链接 – juFo
@juFo,不客气。 –