Comments (3)
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.
I have the same problem. How to get dynamic port in Startup.ConfigureServices method?
from consuldotnet.
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)
- Cannot create an associated check for a service with custom check id HOT 5
- [Bug]: ServiceRegister does not pass WriteOptions to PutRequest, resulting in missing token and datacenter HOT 1
- [Bug]: Consul.Test.SemaphoreTest.Semaphore_OneShot is flaky
- [Bug]: System.IO.IOException: The response ended prematurely HOT 5
- Add `ServiceTags` field to the health endpoint response
- Table showing missing features in consuldotnet
- Add support for Agent Host
- Support for Agent Version Information
- Support for Agent Metrics
- Added Test for Agent Reload
- Support Applying Configuration and Get Configuration
- Support Listing and Deleting Configuration Entries
- Support for Listing Services for Node and Retrieving Nodes that support Mesh Capable Service
- Support Getting Service Configuration
- Wanna do some contribution HOT 1
- [FEATURE REQUEST]: support weights option
- Missing features between Consul.NET (v1.7.14) and target version (v1.9.17) of Consul/Official Client
- FEATURE REQUEST: Support for List Nodes for Connect-capable Service HOT 1
- FEATURE REQUEST: Read LAN Coordinates for a node HOT 1
- FEATURE REQUEST: List Services for Gateway HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from consuldotnet.