Xamarin iOS和.Net Standard 2.0 Dependecy Service

时间:2018-06-12 13:57:22

标签: ios .net xamarin xamarin.ios

我正在使用Xamarin和.net标准2.0创建一个新项目。我的项目有

  
      
  • SLMobileLibrary
  •   
  • SLMobileLibrary.Android
  •   
  • SLMobileLibrary.iOS
  •   

编写这三个项目是为了创建在另一个项目中导入的NuGet包:

  
      
  • SLMobileLibraryTest
  •   
  • SLMobileLibraryTest.iOS
  •   
  • SLMobileLibraryTest.Android
  •   

正如您在此屏幕中看到的那样:

enter image description here

现在,SLMobileLibrary有一个Dependecy Service:

using System;
namespace SLMobileLibrary
{
    public interface ISampleLibrary
    {
        string HelloWorld();
    }
}

SLMobileLibrary.Android有Android的实现:

using System;
using SLMobileLibrary.Android;
using Xamarin.Forms;

[assembly: Dependency(typeof(SampleLibrary))]

    namespace SLMobileLibrary.Android
    {
        public class SampleLibrary : ISampleLibrary
        {
            public SampleLibrary()
            {
            }

            public string HelloWorld()
            {
                return "Hello World! Android";
            }
        }
    }

SLMobileLibrary.iOS具有iOS实现:

using System;
using SLMobileLibrary.iOS;
using Xamarin.Forms;

[assembly: Dependency(typeof(SampleLibrary))]
namespace SLMobileLibrary.iOS
{
    public class SampleLibrary : ISampleLibrary
    {
        public SampleLibrary()
        {
        }

        public string HelloWorld()
        {
            return "Hello World! iOS";
        }
    }
}

所以,在我的App.cs中,我以这种方式回忆起这个方法:

string t = DependencyService.Get<ISampleLibrary>().HelloWorld();

在Android上我没有问题,在iOS上程序崩溃时出现空对象异常,我想因为它无法在iOS上找到实现。但是,如果我尝试将SimpleLibrary.cs放在SLMobileLibraryTest.iOS中,一切都很好。我真的无法理解为什么iOS无法找到实现,如果实现在SLMobileLibrary.iOS中作为SLMobileLibrary.Android。

任何人都可以帮助我吗?我只是附加了源代码,因此您可以下载它并尝试在iOS上编译。 (https://drive.google.com/open?id=12P1zu7BUiwvAkelKAI7fsCxBJYqvmpwZ)。

谢谢!

1 个答案:

答案 0 :(得分:2)

我无法帮助您了解此NRE的原因,但如果您想让它正常工作,那么在iOS上您可以使用[assembly: Dependency(typeof(SampleLibrary))]删除注册,然后添加Xamarin.Forms.DependencyService.Register<SLMobileLibrary.iOS.SampleLibrary>(); AppDelegate的开头。 说到这里,我会尝试使用像Autofac或MvvmLight这样的IoC容器,以及构造函数注入。