c# - Xamarin.Forms DependencyService Get() 方法在 PCL 中返回 Null

标签 c# android xamarin xamarin.forms uwp

我安装了最新的 Xamarin Alpha,但无法使 UWP 和 DependencyService 正常工作。

在 UWP 项目中我有:

Forms.Init(e);

// For release version, doc said debug will do this itself
DependencyService.Register<SpecialInterface>();
IInterface1 iinterface1 = DependencyService.Get<IInterface1>();

这确实找到了接口(interface)指针。

在 PCL 中我有:

IInterface1 iinterface1 = DependencyService.Get<IInterface1>();

在 PCL 中包含的 View 模型中(单击按钮后),它无法返回 null Get<IInterface1>() 的值在 UWP 和 Android 上调用。

以下是 UWP 项目中包含的实现:

using PrismUnityApp2.UWP;
using SharedProject1;
using Xamarin.Forms;

[assembly: Dependency(typeof(SpecialInterface))]

namespace PrismUnityApp2.UWP
{
    public class SpecialInterface : IInterface1
    {
        public SpecialInterface() { }

        public int TestMethod(int i)
        {
            return i;
        }
    }
}

最后,接口(interface)在共享项目中定义如下:

namespace SharedProject1
{
    internal interface IInterface1
    {
        int TestMethod(int i);
    }
}

我的示例“UsingDependencyService”在 Android 中工作,WinPhone 失败,因为 Android 上的 HyperV 已关闭。

我错过了什么?

感谢您的帮助。

使用以下软件包/版本:

  • Prism.Unity.Forms 6.2.0.pre4
  • Prism.Forms 6.1.0.pre4
  • Xamarin.Forms 2.2.0.45
  • Unity 4.0.1
  • Windows 10 UWP

    public void OnNavigatedTo(NavigationParameters parameters)
    {
        if (parameters.ContainsKey("title"))
            Title = (string) parameters["title"] + " and Prism";
    
        IInterface1 iinterface1 = DependencyService.Get<IInterface1>();
        if (iinterface1 != null)
        {
            int value = iinterface1.TestMethod(1);
            Title += " ::: " + value;
        }
    }
    

最佳答案

DependencyService.Get<IInterface1>()调用在 PCL 中返回 null,因为它正在寻找 IInterface1 的不同版本它实际上被定义了多次。

因为IInterface1位于由 PCL 项目和 UWP & Android 项目引用的共享项目中,它与在 PCL 和应用程序项目中分别创建具有相同名称和签名的界面基本相同。然而父程序集是不同的。

如果你要搬家IInterface1到您现有的 PCL 或由现有 PCL 和您的应用程序项目引用的单独 PCL,DependencyService应该能够找到您的平台特定实现,SpecialInterface ,正如预期的那样。

关于c# - Xamarin.Forms DependencyService Get() 方法在 PCL 中返回 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37735586/

相关文章:

c# - 两个日期之间的年、月、日、小时

c# - 网络 API : Configure JSON serializer settings on action or controller level

android - 如何找到执行的文件名和类型

xamarin - 在 Jenkins 上运行 NUnit 测试的问题

java - ImageView 像另一个 ImageView Android 的边框

sqlite - MVVMCross社区SQLite-Net插件-无法打开数据库

c# - WindowsBase.dll 中发生“System.StackOverflowException”

c# - protected 和内部,不 protected 或内部

android - Webview - 窗口已经聚焦,忽略了焦点增益

android - 如果 Android MediaCodec dequeueOutputBuffer() 返回 -3 是什么意思