繁体   English   中英

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

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

我有一个使用Prism和DryIoC作为容器的Xamarin.Forms应用程序。 我有一个值转换器,我需要使用我通过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>
        <ioc:ContainerProvider x:TypeArguments="converters:MyValueConverter"
                               x:Key="myValueConverter" />
    </ContentPage.Resources>
</ContentPage>

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM