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

Xamarin Forms使用Microsoft.Extensions.DependencyInjection注册平台特定服务问题

Xamarin Forms 注册平台特有服务到Microsoft.Extensions.DependencyInjection的实现方案

核心思路

平台特有服务的注册逻辑放到对应平台的入口点执行,共享项目仅负责注册公共服务和视图模型,通过委托将平台侧的注册逻辑注入到共享项目的DI容器构建流程中。

步骤1:修改共享项目Startup类

调整Init方法,新增可接收平台侧服务注册逻辑的委托参数:

public static class Startup
{
    public static IServiceProvider ServiceProvider { get; set; }

    public static IServiceProvider Init(Action<IServiceCollection> platformServiceRegister = null)
    {
        var serviceCollection = new ServiceCollection();
        // 注册共享服务和视图模型
        serviceCollection.ConfigureServices().ConfigureViewModels();
        // 执行平台侧的服务注册逻辑
        platformServiceRegister?.Invoke(serviceCollection);

        ServiceProvider = serviceCollection.BuildServiceProvider();
        return ServiceProvider;
    }
}

步骤2:删除共享项目App中的重复初始化

移除App.xaml.cs构造函数中的Startup.Init();调用,避免重复构建DI容器:

public partial class App : Application
{
    public App()
    {            
        InitializeComponent();
        // 删除该行:Startup.Init();
        MainPage = new AppShell();
    }
}

步骤3:Android平台注册特有服务

在Android项目的MainActivity.cs的OnCreate方法中,执行Startup.Init并注册Android端的服务实现:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

    // 注册Android平台特有服务
    Startup.Init(services => 
    {
        services.AddSingleton<IAuthenticationService, AndroidAuthenticationService>();
        // 其他Android特有服务可在此处添加
    });

    LoadApplication(new App());
}

步骤4:iOS平台注册特有服务

在iOS项目的AppDelegate.cs的FinishedLaunching方法中,执行Startup.Init并注册iOS端的服务实现:

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    global::Xamarin.Forms.Forms.Init();

    // 注册iOS平台特有服务
    Startup.Init(services => 
    {
        services.AddSingleton<IAuthenticationService, IOSAuthenticationService>();
        // 其他iOS特有服务可在此处添加
    });

    LoadApplication(new App());

    return base.FinishedLaunching(app, options);
}

使用方式

完成注册后,可直接在视图模型或共享服务的构造函数中注入IAuthenticationService,DI容器会自动根据当前运行平台匹配对应的实现:

public class LoginViewModel : ViewModelBase
{
    private readonly IAuthenticationService _authService;

    public LoginViewModel(IAuthenticationService authService)
    {
        _authService = authService;
    }

    // 业务逻辑直接使用_authService即可
}

注意事项

  • 共享项目的DependencyInjectionContainer.ConfigureServices方法中无需注册IAuthenticationService,避免覆盖平台侧的注册配置
  • 平台特有服务的生命周期配置规则和共享服务完全一致,可根据需求选择AddSingleton/AddScoped/AddTransient

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 18:57:03