如何使用 Prism/DryIoC 解决 Xamarin.Forms 中 IValueConverter 的依赖关系

How to resolve a dependency in IValueConverter in Xamarin.Forms using Prism/DryIoC

我有一个 Xamarin.Forms 应用程序,它使用 Prism 和 DryIoC 作为容器。我有一个值转换器,我需要在其中使用我通过 IContainerRegistry 注册的服务。

containerRegistry.RegisterSingleton<IUserService, UserService>();

由于 IValueConverter 是由 XAML 而不是 DryIoC 构造的,因此我如何在不必求助于构造函数注入的情况下解决该依赖关系?我可以在 Prism/DryIoC 中使用服务定位器吗?如果是,怎么做?

下面是值转换器代码:

public class MyValueConverter : IValueConverter
{
    private readonly IUserService _userService;

    public MyValueConverter()
    {
        // Ideally, I can use a service locator here to resolve IUserService
        //_userService = GetContainer().Resolve<IUserService>();
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var isUserLoggedIn = _userService.IsLoggedIn;
        if (isUserLoggedIn)
            // Do some conversion
        else
            // Do some other conversion
        ...
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

我鼓励您更新到 7.1 预览版,因为它解决了这个确切的问题。您的转换器就像:

public class MyValueConverter : IValueConverter
{
    private readonly IUserService _userService;

    public MyValueConverter(IUserService userService)
    {
        _userService = userService;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var isUserLoggedIn = _userService.IsLoggedIn;
        if (isUserLoggedIn)
            // Do some conversion
        else
            // Do some other conversion
        ...
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

你的 XAML 看起来像这样:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
            xmlns:converters="clr-namespace:DemoApp.Converters"
            xmlns:ioc="clr-namespace:Prism.Ioc;assembly=Prism.Forms"
            x:Class="DemoApp.Views.AwesomePage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <ioc:ContainerProvider x:TypeArguments="converters:MyValueConverter"
                                   x:Key="myValueConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
</ContentPage>

请务必在更新前查看 release notes,因为该版本还包含一些重大更改。