0

我正在尝试在 Xamarin.Forms (DryIoc.Microsoft.DependencyInjection) 上关注 Prism 上的 DryIoc 和 IServiceProvider但是我正在使用 RefitClientIHttpClientFactory

containerRegistry.RegisterServices(services =>
            {
                services.AddTransient<HttpLoggingHandler>();
                services.AddTransient<AuthorizationDelegatingHandler>();

                services.AddRefitClient<IMyApi>()
                    .ConfigureHttpClient(c =>
                        c.BaseAddress =
                            new Uri(apiBaseUrl))
                    .AddHttpMessageHandler<AuthorizationDelegatingHandler>()
                    .AddHttpMessageHandler<HttpLoggingHandler>()
                    .AddTransientHttpErrorPolicy(builder => builder.WaitAndRetryAsync(new[]
                    {
                        TimeSpan.FromMilliseconds(300),
                        TimeSpan.FromSeconds(600),
                        TimeSpan.FromSeconds(800)
                    }))
                    .AddTransientHttpErrorPolicy(
                        p => p.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)));
            });

我已经添加了

protected override IContainerExtension CreateContainerExtension() => PrismContainerExtension.Current;

当我尝试向 IMyApi 提出请求时。

BaseAddress must be set on the HttpClient instance
  at Refit.RequestBuilderImplementation+<>c__DisplayClass14_0`2[T,TBody].<BuildCancellableTaskFuncForMethod>b__0 (System.Net.Http.HttpClient client, System.Threading.CancellationToken ct, System.Object[] paramList) [0x00030] in /_/Refit/RequestBuilderImplementation.cs:236
4

2 回答 2

0

我使用的是 Unity 而不是 Dryloc,但解决方案是相同的。

关键似乎很大程度上取决于安装正确的软件包。安装这些:

Prism.Forms.Extended

Prism.Unity.Extensions

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    //Omitted Code

    containerRegistry.RegisterServices(serviceCollection =>
    {
        serviceCollection.AddHttpClient<IApiService, ApiService>(client =>
        {
            client.BaseAddress = new Uri("Your Address Here");
        });
    });
}
public class ApiService : IApiService
{
    Func<IApi> _createClient;

    public ApiService(HttpClient client)
    {
        _createClient = () => 
        {
            return RestService.For<IApi>(client, new RefitSettings
            {
                ContentSerializer = new NewtonsoftJsonContentSerializer()
            });
        }
    }

    public IApi GetApi()
    {
        return new Lazy<IApi>(() => _createClient()).Value;
    }
}

这篇文章也提供了部分内容:

https://xamgirl.com/sumption-restful-web-service-xamarin-forms-using-refit-part-2/

于 2021-06-21T13:30:10.497 回答
0

我个人不得不处理所有这些,最终创建了Apizr,其中内置了身份验证和日志记录处理程序,从注册表解析策略以及更多功能,如连接测试、缓存或优先级。如果它可以帮助。

于 2020-11-20T13:40:17.870 回答