【发布时间】:2020-05-21 12:20:21
【问题描述】:
我有一个以 DryIoc 作为容器的 Prism 应用程序。
我希望IHttpClientFactory 向我的类型化客户 提供HttpClients,如下所示:
public class ExampleService : IExampleService
{
private readonly HttpClient _httpClient;
public RepoService(HttpClient client)
{
_httpClient = client;
}
public async Task<IEnumerable<string>> GetExamplesAsync()
{
// Code deleted for brevity.
}
}
在 App.xaml.cs 中,我注册了我的类型化客户端,以便可以将它们注入到具有以下内容的视图模型中:
public partial class App
// ...
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
// Code deleted for brevity.
containerRegistry.Register<IExampleService, ExampleService>();
}
那是在尝试使用IHttpClientFactory之前。
现在,要添加它,我们 should AddHttpClient() IServiceCollection。这就是我认为需要 DryIoc.Microsoft.DependencyInjection 的地方,所以,仍然在 App.xaml.cs 中,我写了以下内容:
public partial class App
// ...
protected override IContainerExtension CreateContainerExtension()
{
var services = new ServiceCollection();
services.AddHttpClient<IExampleService, ExampleService>(c =>
{
c.BaseAddress = new Uri("https://api.example.com/");
});
var container = new Container(CreateContainerRules())
.WithDependencyInjectionAdapter(services);
return new DryIocContainerExtension(container);
}
问题在于,在我的 ExampleService 中,我得到了具有以下规格的 client:
{
"DefaultRequestHeaders":[
],
"BaseAddress":null,
"Timeout":"00:01:40",
"MaxResponseContentBufferSize":2147483647
}
虽然我预计 BaseAddress 为 https://api.example.com/,但 REST API 调用失败。
在将 Prism for Xamarin.Forms 与 DryIoc 一起使用时,使用 IServiceProvider 的正确模式是什么?不幸的是,没有关于以下问题的文档或开源代码,我有点迷失了。
谢谢你,祝你有美好的一天。
更新 #1
根据Dan S. 的指导,DryIoc.Microsoft.DependencyInjection 已被卸载,因此项目在尝试使用IServiceCollection 依赖项之前恢复到其状态(在我的情况下为IHttpClientFactory) ,然后我安装了Prism.Forms.Extended 和后来的Prism.DryIoc.Extensions。
之后 App.xaml.cs 中的 CreateContainerExtension() 变为:
protected override IContainerExtension CreateContainerExtension()
{
var containerExtension = PrismContainerExtension.Current;
containerExtension.RegisterServices(s =>
{
s.AddHttpClient<IExampleService, ExampleService>(c =>
{
c.BaseAddress = new Uri("https://api.example.com/");
});
});
return containerExtension;
}
并且containerRegistry.Register<IExampleService, ExampleService>(); 已从 RegisterTypes() 中删除。
现在ExampleService 终于注入了HttpClient,一切正常。
更新 #2
我使用的与 Prism 相关的唯一软件包是 Prism.DryIoc.Forms 和 Prism.DryIoc.Extensions。 我完全删除了 App.xaml.cs 中 CreateContainerExtension() 的覆盖,并将 RegisterTypes() 重构为
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
// Code deleted for brevity.
containerRegistry.RegisterServices(s =>
{
s.AddHttpClient<IExampleService, ExampleService>(c =>
{
c.BaseAddress = new Uri("https://api.example.com/");
});
});
}
这样我会得到一个NotImplementedException。
但是,通过使用以下内容覆盖 CreateContainerExtension():
protected override IContainerExtension CreateContainerExtension() => PrismContainerExtension.Current;
一切终于恢复正常!
【问题讨论】:
标签: xamarin.forms prism