【问题标题】:Xamarin Dependency Injection fails - crash while trying to get platform specific implementationXamarin 依赖注入失败 - 尝试获取特定于平台的实现时崩溃
【发布时间】:2019-07-09 20:14:33
【问题描述】:

我有一个定义蓝牙控制器的 Xamarin Forms 接口。在尝试创建一个特定于 Android 的实现时,我遵循通常的技术(当我得到这个工作时,我也会做一个 iOS 实现)。

我将我的界面定义如下:

namespace ArduinoRobotController.Models
{
    public interface BluetoothControllerInterface
    {
         List<string> GetPairedDevices();
..

然后我有这样的平台特定实现:

[assembly: Xamarin.Forms.Dependency(typeof(BluetoothControllerInterface))]
namespace ArduinoRobotController.Droid.Implementations
{
    public class BluetoothController : BluetoothControllerInterface
    {
..

最后回到我的一个视图模型,我有这段代码来获取我需要的平台特定实例:

BluetoothControllerInterface bt = Xamarin.Forms.DependencyService.Get<BluetoothControllerInterface>();

它构建并运行,但在上面的行中崩溃。错误状态:

System.MissingMethodException:在 SystemRuntimeType.CreateInstanceMono 中找不到类型 ArduinoRobotController.Models.BluetoothControllerInterface 的默认构造函数

.. 等等

我已经尝试了很多不同的方法来解决这个问题,包括调用以普通代码而不是[assembly 等方式注册实现。对此非常感谢任何帮助。

【问题讨论】:

    标签: dependency-injection xamarin.forms


    【解决方案1】:

    你的注册需要指向具体的类,而不是接口

    [assembly: Xamarin.Forms.Dependency(typeof(BluetoothController))]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 2012-09-19
      • 2018-12-10
      • 1970-01-01
      • 2012-08-13
      • 2017-09-24
      相关资源
      最近更新 更多