gpt4 book ai didi

c# - 向 wpf 行为注入(inject)依赖的干净方法

转载 作者:行者123 更新时间:2023-12-02 01:18:42 25 4
gpt4 key购买 nike

我需要创建自定义 WPF 行为,并在构造函数中注入(inject)一些依赖项,我无法使用构造函数注入(inject),因为我需要在 XAML 中应用它,WPF 使用默认构造函数创建实例。我可以做的一种方法是在默认构造函数或服务定位器中使用容器,但我不想使用这些方法。我可以在属性上使用 [Improt] 并使用 Container.SatisfyImportOnce,但不是很简洁,因为我仍将在构造函数中使用容器。有什么建议吗?

我在我的 WPF 项目中使用 MEF 进行依赖项注入(inject)。

简洁的方式:它应该是可测试的,我应该能够注入(inject)依赖项并且应该在 WPF XAML 中实例化。

最佳答案

正如您所知,您无法使用 Wpf 进行构造函数注入(inject),但可以在 Xaml 中定义属性注入(inject)。我认为一个“简洁”的解决方案是使用 MarkupExtension比如这样:

public sealed class Resolver : MarkupExtension
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
var provideValueTarget = (IProvideValueTarget)serviceProvider
.GetService(typeof(IProvideValueTarget));

// Find the type of the property we are resolving
var targetProperty = provideValueTarget.TargetProperty as PropertyInfo;

if (targetProperty == null)
{
throw new InvalidProgramException();
}

// Find the implementation of the type in the container
return BootStrapper.Container.Resolve(targetProperty.PropertyType);
}
}

并且有这样的行为:

public sealed class InitialiseWebBrowser : Behavior<MyVM>
{
public IQueryHandler<Query.Html, string> HtmlQueryHandler { private get; set; }

// ...
}

我们可以像这样在 Xaml 中配置属性注入(inject):

<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:inf="clr-namespace:abc"
xmlns:behaviours="clr-namespace:def"
x:Class="MyVM">
<i:Interaction.Behaviors>
<behaviours:InitialiseWebBrowser HtmlQueryHandler="{inf:Resolver}"/>
</i:Interaction.Behaviors>

Resolver标记扩展将:

  • 分析它所定义的属性的类型(在示例中 HtmlQueryHandlerIQueryHandler<Query.Html, string> )
  • 从您使用的任何底层容器/解析器解析类型
  • 将其注入(inject)到行为中。

关于c# - 向 wpf 行为注入(inject)依赖的干净方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33097460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com