You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI中DependencyService.Get返回null问题求助

MAUI中DependencyService.Get()返回null的问题排查与修复

核心错误点分析

  • 重复定义接口导致类型不匹配:在Platforms/Android/BluetoothConnector.cs文件末尾,你重复定义了RobotControl命名空间下的IBluetoothConnector接口。这会导致Android实现类继承的是文件内部的重复接口,而调用处使用的是App.xaml.cs里的同名接口,两者属于不同类型实例,DependencyService无法匹配到实现。
  • 实现类缺少public访问修饰符:BluetoothConnector类默认是internal访问级别,DependencyService无法发现并加载这个内部类。
  • (可选)未使用MAUI推荐的依赖注入方式:官方现在更推荐内置DI系统,而非传统DependencyService。

修复步骤

步骤1:删除重复的接口定义

打开Platforms/Android/BluetoothConnector.cs,删除文件末尾重复的RobotControl命名空间和IBluetoothConnector接口定义,只保留实现类部分,同时添加public修饰符并引用正确的接口命名空间:

using Android.Bluetooth;
using Java.Util;
using RobotControl;
using System;
using System.Collections.Generic;
using System.Linq;

[assembly: Dependency(typeof(RobotControl.Platforms.Android.Bluetooth.BluetoothConnector))]
namespace RobotControl.Platforms.Android.Bluetooth
{
    public class BluetoothConnector : IBluetoothConnector
    {
        BluetoothAdapter adapter;
        private const string SspUuid = "00001101-0000-1000-8000-00805f9b34fb";
        private BluetoothSocket? socket;

        public void Connect(string deviceName)
        {
            var device = adapter.BondedDevices.FirstOrDefault(d => d.Name == deviceName);
            if (device == null)
                throw new Exception("Device not found");
            
            socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString(SspUuid));
            socket.Connect();
        }

        public void Write(byte[] data) 
        { 
            if (socket?.IsConnected == true)
            {
                var outputStream = socket.OutputStream;
                outputStream.Write(data, 0, data.Length);
            }
        }

        public List<string> GetConnectedDevices()
        {
            adapter = BluetoothAdapter.DefaultAdapter;
            if (adapter == null) 
            {
                throw new Exception("No Bluetooth adapter");
            }

            if (!adapter.IsEnabled)
            {
                Console.WriteLine("BT is not enabled");
                return new List<string>();
            }

            return adapter.BondedDevices.Select(x => x.Name).ToList();
        }
    }
}

步骤2:确保接口唯一定义

App.xaml.cs中的接口保持原样,确保只有这一处定义:

namespace RobotControl
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            MainPage = new AppShell();
        }
    }

    public interface IBluetoothConnector
    {
        List<string> GetConnectedDevices();
        void Connect(string deviceName);
        void Write(byte[] data);
    }
}

步骤3:(可选)切换到MAUI内置依赖注入(推荐)

  1. 在MauiProgram.cs中注册平台服务:
using RobotControl;
using RobotControl.Platforms.Android.Bluetooth;

namespace RobotControl
{
    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                });

#if ANDROID
            builder.Services.AddSingleton<IBluetoothConnector, BluetoothConnector>();
#endif

            return builder.Build();
        }
    }
}
  1. 在LHand.xaml.cs中通过构造函数注入服务:
namespace RobotControl
{
    public partial class LHand : ContentPage
    {
        private readonly IBluetoothConnector _connector;

        public int L_PinkyAngle;
        public int L_RingAngle;
        public int L_MiddleAngle;
        public int L_IndexAngle;
        public int L_ThumbAngle;
        public int L_RotaAngle;

        public LHand(IBluetoothConnector connector)
        {
            InitializeComponent();
            _connector = connector;
        }

        private async void SPinky_ValueChanged(object sender, ValueChangedEventArgs e)
        {
            if(_connector == null)
            {
                await DisplayAlert("er", "connector is null", "huh");
                return;
            }

            try
            {
                var devices = _connector.GetConnectedDevices();
                string x = string.Join("\n", devices);
                await DisplayAlert("Devices", x, "OK");
            }
            catch(Exception ex)
            {
                await DisplayAlert("Error", ex.Message, "OK");
            }
        }

        // 其他事件方法...
    }
}

步骤4:添加蓝牙权限

在Platforms/Android/AndroidManifest.xml中添加必要权限:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-feature android:name="android.hardware.bluetooth" android:required="false" />

额外注意事项

  • 测试前确保蓝牙已开启,且目标设备已配对
  • Connect方法为同步操作,建议放在后台线程执行避免阻塞UI
  • 对蓝牙操作添加异常捕获,防止应用崩溃

内容的提问来源于stack exchange,提问作者SpeedLight1221

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 20:13:22