我正在使用Xamarin和.net标准2.0创建一个新项目。我的项目有
- 的 SLMobileLibrary
- 的 SLMobileLibrary.Android
- 的 SLMobileLibrary.iOS
编写这三个项目是为了创建在另一个项目中导入的NuGet包:
- SLMobileLibraryTest
- 的 SLMobileLibraryTest.iOS
- 的 SLMobileLibraryTest.Android
正如您在此屏幕中看到的那样:
现在,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)。
谢谢!
答案 0 :(得分:2)
我无法帮助您了解此NRE的原因,但如果您想让它正常工作,那么在iOS上您可以使用[assembly: Dependency(typeof(SampleLibrary))]
删除注册,然后添加Xamarin.Forms.DependencyService.Register<SLMobileLibrary.iOS.SampleLibrary>();
AppDelegate
的开头。
说到这里,我会尝试使用像Autofac或MvvmLight这样的IoC容器,以及构造函数注入。