Giter VIP home page Giter VIP logo

Comments (3)

marcin-krystianc avatar marcin-krystianc commented on August 25, 2024

Hi, as far as I understand your use case you should:

  • Bind the service to port "0"
  • Start the service
  • Read which actual port it was assigned to
  • Provide an actual port to the registration API

Is it what you were after?

from consuldotnet.

bidianqing avatar bidianqing commented on August 25, 2024

I have the same problem. How to get dynamic port in Startup.ConfigureServices method?

from consuldotnet.

dealproc avatar dealproc commented on August 25, 2024

Yeah, I had to do exactly what you mention @marcin-krystianc. In order to achieve it, I had to build an alternative method to AgentServiceRegistration that looks like this:

namespace Consul.AspNetCore {
    using System.Threading;
    using System.Threading.Tasks;

    using Microsoft.AspNetCore.Hosting.Server;
    using Microsoft.AspNetCore.Hosting.Server.Features;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;

    public class AgentServiceRegistrationWithDynamicPortHostedService : IHostedService {
        private readonly IServer _server;
        private readonly IConsulClient _consulClient;
        private readonly AgentServiceRegistration _serviceRegistration;
        private readonly ILogger _log;
        private readonly IHostApplicationLifetime _hostApplicationLifetime;

        public AgentServiceRegistrationWithDynamicPortHostedService(ILoggerFactory loggerFactory,
            IHostApplicationLifetime hostApplicationLifetime,
            IServer server,
            IConsulClient consulClient,
            AgentServiceRegistration serviceRegistration) {
            _log = loggerFactory.CreateLogger<AgentServiceRegistrationWithDynamicPortHostedService>();
            _hostApplicationLifetime = hostApplicationLifetime;
            _log.LogCritical("Logger instantiated.");
            _server = server;
            _consulClient = consulClient;
            _serviceRegistration = serviceRegistration;
        }

        public Task StartAsync(CancellationToken cancellationToken) {
            _hostApplicationLifetime.ApplicationStarted.Register(() => {
                _log.LogInformation("Registering with Consul.");
                var serverAddressesFeature = _server.Features.Get<IServerAddressesFeature>();
                _log.LogInformation("Number of Uris: {@NumberOfUris}", serverAddressesFeature.Addresses.Count);
                var possiblePorts = serverAddressesFeature.Addresses.Select(a => new Uri(a).Port).Distinct();
                _serviceRegistration.Port = possiblePorts.FirstOrDefault();
                _log.LogInformation("Reporting as bound to port: {@port}", _serviceRegistration.Port);

                _log.LogInformation("Updating endpoints, replacing {port} with actual port number.");
                if (_serviceRegistration.Check != null) {
                    _serviceRegistration.Check.HTTP = (_serviceRegistration.Check.HTTP ?? "").Replace("{port}", _serviceRegistration.Port.ToString());
                    _serviceRegistration.Check.TCP = (_serviceRegistration.Check.TCP ?? "").Replace("{port}", _serviceRegistration.Port.ToString());
                }
                foreach (var x in _serviceRegistration.Checks ?? new AgentServiceCheck[0]) {
                    x.HTTP = (x.HTTP ?? "").Replace("{port}", _serviceRegistration.Port.ToString());
                    x.TCP = (x.TCP ?? "").Replace("{port}", _serviceRegistration.Port.ToString());
                }

                _consulClient.Agent.ServiceRegister(_serviceRegistration, CancellationToken.None).GetAwaiter().GetResult();
            });

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken) {
            return _consulClient.Agent.ServiceDeregister(_serviceRegistration.ID, cancellationToken);
        }
    }

    public static class AdditionalServiceCollectionExtensions {
        public static IServiceCollection AddConsulServiceRegistrationWithDynamicPort(this IServiceCollection services, Action<AgentServiceRegistration> configure) {
            var registration = new AgentServiceRegistration();

            configure.Invoke(registration);

            return services
                .AddSingleton(registration)
                .AddHostedService<AgentServiceRegistrationWithDynamicPortHostedService>();
        }
    }
}

The key point with this... the app needs to be fully online before you can read the resolved IP Port and register. I didn't see an alternative way to gain the resolved IP. If someone has more information on how to better implement this, I'm game to listen and learn.

from consuldotnet.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.