Last active
June 28, 2020 21:01
-
-
Save GeradeDev/09ec4d1591dde6d4c0ffbf7d0aa11a6c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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