Maui:CreateMauiApp 之外的 AddHttpClient 和 AddSingleton

问题描述 投票:0回答:1

我正在使用 Prism 和 DryIoc 将应用程序从 Xamarin Forms 迁移到 Maui,并且需要在 CreateMauiApp 函数之外注册服务和 HttpClientFactory(原因是我不知道启动时 HttpClient 的端点 - 它是作为应用程序加载后的另一个进程)。

我可以通过 Prism 和 DryIoc 使用 Prism 的 ContainerLocator 来完成此操作...

var containerRegistry = ContainerLocator.Current;

containerRegistry.RegisterSingleton<IApiManager, ApiManager>();

containerRegistry.RegisterServices(serviceCollection =>
{
    serviceCollection.AddHttpClient<IApiService, ApiService>(client =>
    {
        client.BaseAddress = new Uri(uri);
    }
});

...但是无法使用 IServiceProvider 注册新服务。

有人对如何实现这一目标有任何想法吗?

提前致谢。

xamarin.forms dependency-injection maui httpclientfactory
1个回答
0
投票

这更像是“评论”而不是答案。 通常我会做这样的事情:

builder.Services.AddSingleton(new HttpClient() { BaseAddress = new Uri("..."), Timeout...

在我的 MauiProgram.cs 中。

然后将其注入其他服务的构造函数中,或多或少像这样:

readonly HttpClient httpClient;
public MyService(HttpClient httpClient){
   this.httpClient = httpClient;
}

而且它有效。

但是您可以添加一个 Singleton 服务,其中包含 HttpClient,而不是注入 HttpClient。

class MyHttpClientService : IMyHttpClientService 
{
    HttpClient httpClient;
    //Get method - use it in your other services constructors
    //Init - use it when you can (after your "load")
}

您可以注入您的服务,而不是直接注入客户端:

readonly HttpClient httpClient;
public MyService(IMyHttpClientService myHttpClientService){
   this.httpClient = myHttpClientService.GetHttpClient();
}

我必须警告您,某些网络更改可能会使您的 HttpClient 不再可用,您将不得不重新创建它。这是我所知道的唯一缺点。除了处理它的额外工作之外。

这就是我接受这一切的原因:

我使用 MAUI 进行移动开发。

虽然您可以在 Linux 服务器上运行 .NET Web API,并且每秒发送 100 多个“new HttpClient()”垃圾邮件,并且可以侥幸逃脱,但在移动设备上情况却有所不同。

HttpClient
是,
HttpMessageInvoker
,并且因为它实现了
IDisposable
,它可以欺骗你,你可以创建任意数量的实例,并在你想要的时候毫无问题地处理它们。

但是,在移动设备中,您有不同版本的 Android、不同版本的 Linux、不同的硬件、不同的驱动程序等等......

在IOS上你需要担心的变量较少,但是当你拉线时,情况并没有好多少。

最终结果 - 当您处置某些资源时,操作系统何时以及是否会收回它,是很难预测的。当你开始收到随机运行时异常时,因为你没有套接字,没有什么可以再修复它了。

我的信息是一年多前的,也许现在有人已经为 MAUI 实现了一个可用的 http 客户端工厂。只要确保它在实际的物理设备上进行了测试即可。不是模拟器或 Windows 机器。

© www.soinside.com 2019 - 2024. All rights reserved.