【问题标题】:Resolving dependencies in XAML using Autofac使用 Autofac 解决 XAML 中的依赖关系
【发布时间】:2012-05-06 08:50:15
【问题描述】:

我的应用程序中有一个类 MyResource,如下所示:

public class MyResource : IMyResource
{
    // ... whatever ...
}

当我在 App.xaml.cs 中初始化我的应用程序时,我使用 Autofac 有类似的东西:

builder.Register<IMyResource>(container => new MyResource());

现在我需要在我的 WPF 应用程序的 Window 中添加一个 StaticResource,如下所示:

<Window.Resources>
    <local:MyResource x:Key="MyResource" />
</Window.Resources>

当然,整个想法是在这里引用MyResource 的具体实例。此外,我可能需要在我的应用程序的不同Windows 或UserControls 中使用MyResource 的实例。因此,我想使用MyResource 的实例作为StaticResourceWindow,通过Autofac 容器解析。我怎样才能做到这一点?

我正在考虑在 Window 的代码隐藏中添加资源,但它可能会在我的容器上创建我不想要的依赖项。

当我初始化应用程序时,我也在考虑在 App.xaml.cs 中做类似的事情:

App.Current.MainWindow.Resources.Add("MyResource", container.Resolve<IMyResource>());

但是当我在我的 XAML 中使用资源时

<ListBox ItemsSource="{Binding Source={StaticResource ResourceKey=MyResource}}"/>

我收到XAMLParseException 内部异常消息,指出找不到名为 MyResource 的资源。而且即使它起作用了,我也觉得它有点臭。

那么如何实现呢?只有可能吗?如果不是,最好的方法是什么?

【问题讨论】:

    标签: c# wpf xaml dependency-injection autofac


    【解决方案1】:

    按照这些步骤进行

    • 向 Autofac 注册 MyWindowMyResource
    • IMyResource 放在MyWindow 的构造函数中(是的,您正在修改后面的代码,但不是指您的容器。如果您不能在代码隐藏中包含代码-也许您是UserControl --然后确保有人在某处设置DataContext
    • DataContext 设置为IMyResource 的具体实例(在构造函数中),或者如果您使用的是MVVM,则将该实例放入您的视图模型(也将使用Autofac 注册)。
    • 解决MyWindow

    在代码中:

    MyWindow(IMyResource myResource) : this()
    {
      DataContext = myResource;
    }
    

    如果您使用的是 ViewModel(也在 Autofac 中注册):

    MyWindow(MyViewModel viewModel) : this()
    {
      DataContext = viewModel;
    }
    

    将此行添加到您的 XAML:

    <Window.DataContext><local:IMyResource></Window.DataContext>
    

    或者这个:

    <Window.DataContext><local:MyViewModel></Window.DataContext>
    

    然后你对ListBox 的标记就变得微不足道了:

    <ListBox ItemsSource="{Binding}"/>
    

    或者,使用视图模型,例如属性Items,它也一样好:

    <ListBox ItemsSource="{Binding Items}"/>
    

    【讨论】:

      猜你喜欢
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      相关资源
      最近更新 更多