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

jon*_*tez 5 c# prism xamarin xamarin.forms dryioc

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

containerRegistry.RegisterSingleton<IUserService, UserService>();
Run Code Online (Sandbox Code Playgroud)

由于 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_* S. 10

我鼓励您更新到 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

您的 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>
Run Code Online (Sandbox Code Playgroud)

不过,请务必在更新之前查看发行说明,因为该版本还包含一些重大更改。