如何在我的Azure Service Fabric应用程序中注入IHttpClientFactory?

时间:2019-03-11 15:39:48

标签: c# autofac azure-service-fabric asp.net-core-2.2

我正在尝试在解决方案中使用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的自定义客户端以进行注入?我应该怎么做?有什么例子吗?谢谢。

2 个答案:

答案 0 :(得分:1)

请在此处查看Interface documentation

所以回答您的问题:

1)在“ ConfigureServices”方法调用IServiceCollection中使用.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);
}

P.S。 请确保添加-Autofac.Extensions.DependencyInjection nuget包,以便能够使用AutofacServiceProvider类。

答案 1 :(得分:0)

除了使用类似于创建普通 Asp.Net Core Service Fabric 项目时所获得的基于 WebHostBuilder 的解决方案之外,您还可以选择这样做

public class HttpClientModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        
        builder.Register(_ =>
            {
                var services = new ServiceCollection();
                services.AddHttpClient();
                var containerBuilder = new ContainerBuilder();
                containerBuilder.Populate(services);
                var container = containerBuilder.Build();
                return new AutofacServiceProvider(container);
            })
            .As<IServiceProvider>()
            .SingleInstance();


        builder.Register(ctx =>
        {
            var scope = ctx.Resolve<IComponentContext>();
            var provider = scope.Resolve<IServiceProvider>();
            var factory = provider.GetService<IHttpClientFactory>();
            return factory.CreateClient();
        }).As<HttpClient>();
    }
}