예제 #1
0
        public static IFixerBuilder AddConsul(this IFixerBuilder builder, ConsulOptions options,
                                              HttpClientOptions httpClientOptions)
        {
            builder.Services.AddSingleton(options);
            if (!options.Enabled || !builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            if (httpClientOptions.Type?.ToLowerInvariant() == "consul")
            {
                builder.Services.AddTransient <ConsulServiceDiscoveryMessageHandler>();
                builder.Services.AddHttpClient <IConsulHttpClient, ConsulHttpClient>()
                .AddHttpMessageHandler <ConsulServiceDiscoveryMessageHandler>();
                builder.Services.AddHttpClient <IHttpClient, ConsulHttpClient>()
                .AddHttpMessageHandler <ConsulServiceDiscoveryMessageHandler>();
            }

            builder.Services.AddTransient <IConsulServicesRegistry, ConsulServicesRegistry>();
            builder.Services.AddSingleton <IConsulClient>(c => new ConsulClient(cfg =>
            {
                if (!string.IsNullOrEmpty(options.Url))
                {
                    cfg.Address = new Uri(options.Url);
                }
            }));

            var registration = builder.CreateConsulAgentRegistration(options);

            if (registration is null)
            {
                return(builder);
            }

            builder.Services.AddSingleton(registration);
            builder.AddBuildAction(sp =>
            {
                var consulRegistration = sp.GetService <AgentServiceRegistration>();
                var client             = sp.GetService <IConsulClient>();

                client.Agent.ServiceRegister(consulRegistration);
            });

            return(builder);
        }