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

如何在Xamarin.Forms Prism DryIoC环境下使用.AddHttpClient方法

前置依赖安装

首先需要额外安装两个NuGet包:

  • Microsoft.Extensions.Http
  • DryIoc.Microsoft.DependencyInjection

注册代码修改

在App.xaml.cs的RegisterTypes方法中按照如下逻辑修改即可:

using Microsoft.Extensions.DependencyInjection;
using DryIoc.Microsoft.DependencyInjection;

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    // 初始化微软DI服务集合
    var serviceCollection = new ServiceCollection();

    // 配置类型化HttpClient,添加自定义HttpMessageHandler
    serviceCollection.AddHttpClient<IHrService, HrService>(client =>
    {
        // 配置HttpClient基础参数,示例如下
        client.BaseAddress = new Uri("https://your-api-base-url.com/");
        client.Timeout = TimeSpan.FromSeconds(30);
        client.DefaultRequestHeaders.Add("Accept", "application/json");
    })
    // 添加你自定义的HttpMessageHandler,支持链式添加多个
    .AddHttpMessageHandler(() => new YourCustomMessageHandler());

    // 将服务集合中的注册项填充到DryIoc容器中
    containerRegistry.GetContainer().Populate(serviceCollection);

    // 其余原有服务注册逻辑保持不变
    // ...
}

注意事项

如果你的自定义HttpMessageHandler本身也需要依赖其他注入服务,只需先将Handler注册到服务集合中,再通过泛型方法引用即可:

// 先注册自定义Handler
serviceCollection.AddTransient<YourCustomMessageHandler>();

// 配置HttpClient时直接引用
serviceCollection.AddHttpClient<IHrService, HrService>(/*配置逻辑*/)
    .AddHttpMessageHandler<YourCustomMessageHandler>();

完成以上配置后,直接在需要的位置构造注入IHrService即可正常使用配置好的HttpClient实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:36:03