我有一个使用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();
}
}
答案 0 :(得分:2)
我建议您更新到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>
请务必在更新之前查看release notes,因为该版本还包含一些重大更改。