我有一个使用DryIoc容器的Prism应用程序。
我想让
在 App.xaml.cs 中,我注册了我的类型化客户端,以便可以使用以下方式将它们注入到视图模型中:
问题在于,我的ExampleService中使用了以下规格的client:
此后,在 App.xaml.cs 中的 CreateContainerExtension() 变为:
这样我会得到一个“NotImplementedException”的抛出。然而,通过以下方式重写
IHttpClientFactory
为我的类型化客户端提供HttpClient
, 类似这样:
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
之前,就是这样。
现在,要添加它,我们应该在IServiceCollection
上使用AddHttpClient()
。这就是我认为需要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调用失败了。
在使用DryIoc和Prism for Xamarin.Forms时,使用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;
}
现在从RegisterTypes()中删除了containerRegistry.Register<IExampleService, ExampleService>();
。
现在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;
一切终于恢复正常了!