private static ServiceRegistration CreateConsulAgentRegistration(this IConveyBuilder builder, ConsulOptions options) { var enabled = options.Enabled; var consulEnabled = Environment.GetEnvironmentVariable("CONSUL_ENABLED")?.ToLowerInvariant(); if (!string.IsNullOrWhiteSpace(consulEnabled)) { enabled = consulEnabled is "true" or "1"; } if (!enabled) { return(null); } if (string.IsNullOrWhiteSpace(options.Address)) { throw new ArgumentException("Consul address can not be empty.", nameof(options.PingEndpoint)); } builder.Services.AddHttpClient <IConsulService, ConsulService>(c => c.BaseAddress = new Uri(options.Url)); if (builder.Services.All(x => x.ServiceType != typeof(ConsulHostedService))) { builder.Services.AddHostedService <ConsulHostedService>(); } string serviceId; using (var serviceProvider = builder.Services.BuildServiceProvider()) { serviceId = serviceProvider.GetRequiredService <IServiceId>().Id; } var registration = new ServiceRegistration { Name = options.Service, Id = $"{options.Service}:{serviceId}", Address = options.Address, Port = options.Port, Tags = options.Tags, Meta = options.Meta, EnableTagOverride = options.EnableTagOverride, Connect = options.Connect?.Enabled == true ? new Connect() : null }; if (!options.PingEnabled) { return(registration); } var pingEndpoint = string.IsNullOrWhiteSpace(options.PingEndpoint) ? string.Empty : options.PingEndpoint.StartsWith("/") ? options.PingEndpoint : $"/{options.PingEndpoint}"; if (pingEndpoint.EndsWith("/")) { pingEndpoint = pingEndpoint.Substring(0, pingEndpoint.Length - 1); } var scheme = options.Address.StartsWith("http", StringComparison.InvariantCultureIgnoreCase) ? string.Empty : "http://"; var check = new ServiceCheck { Interval = ParseTime(options.PingInterval), DeregisterCriticalServiceAfter = ParseTime(options.RemoveAfterInterval), Http = $"{scheme}{options.Address}{(options.Port > 0 ? $":{options.Port}" : string.Empty)}" + $"{pingEndpoint}" }; registration.Checks = new[] { check }; return(registration); }