簡體   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