这是我如何使用 Unity 和 Template 10 的一个小例子。
1.创建一个视图模型
我还创建了一个 DataService 类来创建人员列表。看一下 [Dependency] 注释。
public class UnityViewModel : ViewModelBase
{
public string HelloMessage { get; }
[Dependency]
public IDataService DataService { get; set; }
private IEnumerable<Person> people;
public IEnumerable<Person> People
{
get { return people; }
set { this.Set(ref people, value); }
}
public UnityViewModel()
{
HelloMessage = "Hello !";
}
public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode,
IDictionary<string, object> suspensionState)
{
await Task.CompletedTask;
People = DataService.GetPeople();
}
}
2. 创建一个类来创建和填充你的 UnityContainer
将 UnityViewModel 和 DataService 添加到 unityContainer。创建一个属性来解析 UnityViewModel。
public class UnitiyLocator
{
private static readonly UnityContainer unityContainer;
static UnitiyLocator()
{
unityContainer = new UnityContainer();
unityContainer.RegisterType<UnityViewModel>();
unityContainer.RegisterType<IDataService, RuntimeDataService>();
}
public UnityViewModel UnityViewModel => unityContainer.Resolve<UnityViewModel>();
}
3. 将 UnityLocator 添加到您的 app.xaml
<common:BootStrapper x:Class="Template10UWP.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:common="using:Template10.Common"
xmlns:mvvmLightIoc="using:Template10UWP.Examples.MvvmLightIoc"
xmlns:unity="using:Template10UWP.Examples.Unity">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles\Custom.xaml" />
<ResourceDictionary>
<unity:UnitiyLocator x:Key="UnityLocator" />
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
<!-- custom resources go here -->
</ResourceDictionary>
</Application.Resources>
4.创建页面
使用 UnityLocator 将 UnityViewModel 设置为 DataContext 并将属性绑定到控件
<Page
x:Class="Template10UWP.Examples.Unity.UnityMainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Template10UWP.Examples.Unity"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
DataContext="{Binding Source={StaticResource UnityLocator}, Path=UnityViewModel}"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding HelloMessage}" HorizontalAlignment="Center"
VerticalAlignment="Center" />
<ListBox Grid.Row="1" ItemsSource="{Binding People}" DisplayMemberPath="FullName">
</ListBox>
</Grid>
页面解析 UnityViewModel 时会自动注入 DataService。
现在回答你的问题
这取决于项目如何相互依赖。我不确定什么是最好的解决方案,但我想我会尝试使用一个 UnityContainer 并将其放在核心库中。
我希望我的例子回答了这个问题
我希望我的例子回答了这个问题