Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public static IServiceCollection AddConsul(this IServiceCollection serviceCollection)
{
IConfiguration configuration;
using (var serviceProvider = serviceCollection.BuildServiceProvider())
{
configuration = serviceProvider.GetService<IConfiguration>();
}
ConsulOptions consulConfigOptions = configuration.GetOptions<ConsulOptions>("Consul");
serviceCollection.Configure<ConsulOptions>(configuration.GetSection("Consul"));
serviceCollection.AddTransient<IConsulServices, ConsulServices>();
serviceCollection.AddHttpClient<IConsulHttpClient, ConsulHttpClient>();
return serviceCollection.AddSingleton<IConsulClient>(c => new ConsulClient(cfg =>
{
if (!string.IsNullOrEmpty(consulConfigOptions.Host))
{
cfg.Address = new Uri(consulConfigOptions.Host);
}
}));
}
public static string UseConsul(this IApplicationBuilder app)
{
using (var scope = app.ApplicationServices.CreateScope())
{
var Iconfig = scope.ServiceProvider.GetService<IConfiguration>();
var config = Iconfig.GetOptions<ConsulOptions>("Consul");
var appOptions = Iconfig.GetOptions<AppOptions>("App");
if (!config.Enabled)
return String.Empty;
Guid serviceId = Guid.NewGuid();
string consulServiceID = $"{config.Service}:{serviceId}";
var client = scope.ServiceProvider.GetService<IConsulClient>();
var consulServiceRistration = new AgentServiceRegistration
{
Name = config.Service,
ID = consulServiceID,
Address = config.Address,
Port = config.Port
};
client.Agent.ServiceRegister(consulServiceRistration);
return consulServiceID;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.