3

我有 Unity 2.0 在 App.xaml.cs 中运行良好,可以在该类中注册和解析。

我的问题是关于最佳实践。

我有许多用户控件和其他类也需要解决一些相同的和新的接口 <-> 实现。问题是无法访问我在 App.xaml.cs 中创建的 Unity 容器。

我不能使用构造函数或属性注入来传递容器引用。

  1. 太多了(这是一个大项目)
  2. 用户控件是通过 xaml 添加的
  3. 项目中有几个非常松散相关的“模块”可以共享相同的容器配置。

我宁愿不从需要访问容器的每个对象中的配置文件重新创建容器。

当需要相同的容器作为同一程序集的各种“模块”中的服务时,是否有任何最佳实践建议?

谢谢。

4

1 回答 1

4

我相信至少在代码中将它们聚集在一起Controls并且是痛苦的。IoC可能有人会争论,但 IMO 避免这种痛苦的最佳做法是MVVM。您将拥有可以自由构建的视图模型,Unity并将您需要的所有内容注入其中。您将拥有绑定到 viewModel 的视图,而无需知道任何控制反转的情况。

更新:根据评论:

应用程序.xaml.cs:

    private void HandleStartup(object sender, StartupEventArgs e)
    {
        var container = CreateContainer(); // create IoC container
       var mainViewModel = container.Resolve<MainViewModel>();
        var shell = new Shell { DataContext = mainViewModel }; // main View
        MainWindow = shell;
        shell.Show();
    }

外壳 XAML 示例:

<UserControl>
     <StackPanel>
          <ContentPresenter Content="{Binding ViewModel1}" />
          <ContentPresenter Content="{Binding ViewModel2}" />
          <ContentPresenter Content="{Binding ViewModel3}" />
     </StackPanel>
</UserControl>

主视图模型:

public class MainViewModel
{
     public ViewModel1 ViewModel1 { get; private set; }
     public ViewModel2 ViewModel2 { get; private set; }
     public ViewModel3 ViewModel3 { get; private set; }

     // this will be handled by IoC container
     public MainViewModel(ViewModel1 viewModel1, ViewModel2 viewModel2, ViewModel3 viewModel3)
    {
        ViewModel1 = viewModel1;
        ViewModel2 = viewModel2;
        ViewModel3 = viewModel3;
    }

通过这种方式,您的视图将不知道 IoC,并且您想要在 viewModels 中的所有内容都将成功注入。

UPDATE2 DataTemplating 汇集ViewsViewModels

应用程序.xaml

<Application.Resources>
    <DataTemplate DataType="{x:Type local:ViewModel1}">
        <View1 />
    </DataTemplate>
</Application.Resources>
于 2011-03-01T20:26:36.440 回答