Как внедрить IHttpClientFactory в мое приложение Azure Service Fabric? - PullRequest
1 голос
/ 11 марта 2019

Я пытаюсь использовать IHttpClientFactory в своем решении вместо просто экземпляров HttpClient.

startup.cs:

services.AddHttpClient("Test", client =>
{
    client.BaseAddress = new Uri("http://localhost:57863");
    client.Timeout = new TimeSpan(0, 0, 30);
    client.DefaultRequestHeaders.Clear();
});

и в моих службах, нуждающихся вHttpClient:

private readonly Uri _clusterLinuxUri;
private readonly IHttpClientFactory _clientFactory;
public LiasseService(ConfigSettings settings, IHttpClientFactory clientFactory)
{
    _clusterLinuxUri = new Uri($"{settings.LinuxClusterEndpoint}");
    _clientFactory = clientFactory;
}
public async Task<LiasseDetails> CreateLiasseAsync(LiasseCreate liasseData)
{
    using (var response = await _clientFactory.CreateClient("Test")
        .PostAsJsonAsync($"{_clusterLinuxUri}{_createPath}", liasseData))
    {
        await response.CheckHttpError($"{nameof(CreateLiasseAsync)} - error in CL");
        var detailsList = await response.Content.ReadAsAsync<LiasseDetailsList>();
        return detailsList.Details.FirstOrDefault();
    }
}

Часть, которую я не выяснил, это как внедрить ее в Autofac.

program.cs

    private static void Main()
    {
        try
        {
            var builder = new ContainerBuilder();
            builder.RegisterModule(new GlobalAutofacModule());
            builder.RegisterServiceFabricSupport();
            builder.RegisterStatelessService<FacadeCore>("xxx.FacadeCoreType");

            using (builder.Build())
            {
                ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(FacadeCore).Name);
                Thread.Sleep(Timeout.Infinite);
            }
        }
        catch (Exception e)
        {
            ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
            throw;
        }
    }


    public class GlobalAutofacModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<ConfigSettings>();

            builder.RegisterType<PaymentService>().As<IPaymentService>();
            builder.RegisterType<MailerService>().As<IMailerService>();
            builder.RegisterType<LiasseService>().As<ILiasseService>();
            builder.RegisterType<AnalyseFinanciereService>().As<IAnalyseFinanciereService>();
            builder.RegisterType<ApimService>().As<IApimService>();

            builder.RegisterType<UserRepository>().As<IUserRepository>();
            builder.RegisterType<ApplicationProcessRepository>().As<IApplicationProcessRepository>();
            builder.RegisterType<LiasseRepository>().As<ILiasseRepository>();

            builder.RegisterType<CustomUserIdProvider>().As<IUserIdProvider>();
        }
    }

Должен ли я создатькакой-нибудь пользовательский клиент, который реализует IHttpClientFactory, чтобы иметь возможность внедрить его?Как мне это сделать?Есть примеры?Спасибо.

1 Ответ

1 голос
/ 11 марта 2019

См. Документация по интерфейсу здесь

Итак, чтобы ответить на ваш вопрос:

1) Использование IServiceCollection из вызова метода 'ConfigureServices' .AddHttpClient()

2) Создайте новый конструктор контейнеров Autofac и заполните его IServiceCollection, упомянутым выше

3) Из метода ConfigureServices верните новый AutofacServiceProvider

public IServiceProvider ConfigureServices(IServiceCollection services)
{
   ...

   services.AddHttpClient();

   var containerBuilder = new ContainerBuilder();

   containerBuilder.Populate(services);

   var container = containerBuilder.Build();

   return new AutofacServiceProvider(container);
}

PS Убедитесь, чтоadd - Autofac.Extensions.DependencyInjection пакет nuget, чтобы можно было использовать AutofacServiceProvider class.

...