How to self register a service with Consul

妖精的绣舞 提交于 2019-12-02 21:26:07

First of all I recommend to use Consul.NET to interact with Consul. Using it, a service registration may look like:

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

using (var client = new ConsulClient())
{
    await client.Agent.ServiceRegister(registration);
}

Now let's integrate this code into ASP.NET Core startup process with help of DI and loose coupling. Read your json file into ConsulOptions instance (DTO without any logic):

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

Incapsulate all Consul-related logic in class ConsulService accepting ConsulOptions as dependence:

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

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

Add the class itself to DI container:

services.AddTransient<ConsulService>();

Then create an extention method of IApplicationBuilder and call it:

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

In ConsulRegister implementation we add our hooks on application start/stop:

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
    }
}

Locking absence and static fields are OK because of Startup class is executed once on application start. Don't forget to de-register the API in OnStopping method!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!