How to register a service with the Consul

I am trying to self register my ASP.NET Core application in the Consul registry at startup and cancel it at shutdown.

From here I can understand that calling http api [ put /v1/agent/service/register] may be a way (or maybe not!).

From my application, I decided to target the class Startupstarting from adding my .jsonfile

public Startup(IHostingEnvironment env)
{
   var builder = new Configuration().AddJsonFile("consulconfig.json");
   Configuration = builder.Build();
}

But now I'm stuck, because the method ConfigureServicestells me that I am adding services to the container, and the method Configureis where I configure the HTTP request pipeline.

Anyone who pointed me in the right direction, online readings, examples, etc.

+4
1

, Consul.NET   . , :

var registration = new AgentServiceRegistration
{
    Name = "foo",
    Port = 4242,
    Address = "http://bar"
};

await client.Agent.ServiceRegister(registration);

ASP.NET Core DI . json ConsulOptions (DTO - ):

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();
    services.Configure<ConsulOptions>(Configuration);
}

ConsulService, ConsulOptions :

public class ConsulService : IDisposable
{
    public ConsulService(IOptions<ConsulOptions> optAccessor) { }

    public void Register() 
    {
        //possible implementation of synchronous API
        client.Agent.ServiceRegister(registration).GetAwaiter().GetResult();
    }
}

DI:

services.AddTransient<ConsulService>();

IApplicationBuilder :

public void Configure(IApplicationBuilder app)
{
    app.ConsulRegister();
}

ConsulRegister / :

public static class ApplicationBuilderExtensions
{
    public static ConsulService Service { get; set; }

    public static IApplicationBuilder ConsulRegister(this IApplicationBuilder app)
    {
        //design ConsulService class as long-lived or store ApplicationServices instead
        Service = app.ApplicationServices.GetService<ConsulService>();

        var life = app.ApplicationServices.GetService<IApplicationLifetime>();

        life.ApplicationStarted.Register(OnStarted);
        life.ApplicationStopping.Register(OnStopping);

        return app;
    }

    private static void OnStarted()
    {
        Service.Register(); //finally, register the API in Consul
    }
}

, Startup . API OnStopping!

+6

Source: https://habr.com/ru/post/1654444/


All Articles