开发者社区> 问答> 正文

如何使用Xamarin Prism在Android上设置ParentActivityOrWindow

我正在重写我的香草Xamarin应用程序以使用Prism库。

当前的应用程序使用Azure ADB2C使用此框架进行授权。

Android需要设置其父窗口,这是通过将以下代码添加到Android项目的MainActivity.cs中来实现的:


var authenticationService = DependencyService.Get<IAuthenticationService>();
authenticationService.SetParent(this);
这不适用于Prism应用,authenticationService为null。作为记录,此处使用的DependencyService是Xamarin.Forms.DependencyService。

我还尝试了Prism文档中的示例,并将此代码放入AndroidInitializer中:

public void RegisterTypes(IContainerRegistry container)
{
    // Register any platform specific implementations
    container.RegisterSingleton<IAuthenticationService, B2CAuthenticationService>("B2CAuthenticationService");
    var authService = Container.Resolve<IAuthenticationService>();

    authService.SetParent(this);
}

在此代码中,容器(DryIoC容器)没有为Resolve定义。

为了完整起见,这是我的App.cs RegisterTypes:

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    containerRegistry.RegisterSingleton<IAuthenticationService, B2CAuthenticationService>();
    ...
    ...
}

展开
收起
Puppet 2020-01-17 09:05:31 572 0
1 条回答
写回答
取消 提交回答
  • 您在这里做出一些错误的假设。首先,您会注意到IContainerRegistry特别具有名称Registry,这意味着我们不希望您在此处解析类型。这就是为什么您没有看到Resolve方法,而是看到IContainerProvider实例的原因。

    通过设计,Prism不再直接与Xamarin.Forms DependencyService一起使用,因为这是一个完整的反模式。也就是说,如果您遵循有关注册平台特定类型的指导,则可以看到如何使用IPlatformInitializer注册平台特定类型。重要的是要在这里意识到在PrismApplication中调用RegisterTypes之前先调用IPlatformInitializer。

    我建议建议引入一个IParentWindowProvider,例如:

    
    public interface IParentWindowProvider
    {
        object Parent { get; }
    }
    

    然后,您可以在Android上实现此功能,例如:

    public class MainActivity : IPlatformInitializer, IParentWindowProvider
    {
        object IParentWindowProvider.Parent => this;
    
        void IPlatformInitializer.RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterInstance<IParentWindowProvider>(this);
        }
    }
    

    然后,在您的应用程序中,您可以执行以下操作:

    protected override void OnInitialized()
    {
        if(Container.IsRegistered<IParentWindowProvider>())
        {
            var provider = Container.Resolve<IParentWindowProvider>();
            var authService = Container.Resolve<IAuthenticationService>();
            authService.SetParent(provider.Parent);
        }
    }
    

    有关更多信息,请务必查看相关文档和样本

    https://prismlibrary.com/docs/xamarin-forms/dependency-injection/platform-specific-services.html https://github.com/PrismLibrary/Prism-Samples-Forms/tree/master/03-PlatformSpecificServices

    2020-01-17 09:06:16
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
58同城Android客户端Walle框架演进与实践之路 立即下载
Android组件化实现 立即下载
蚂蚁聚宝Android秒级编译——Freeline 立即下载