public Task StartAsync(CancellationToken cancellationToken)
        {
            this.logger.LogInformation("{LogKey:l} hosted service started", LogKeys.ServiceDiscovery);

            this.cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            // https://github.com/cecilphillip/aspnet-servicediscovery-patterns/blob/master/self_registration/src/SchoolAPI/Infrastructure/ConsulHostedService.cs

            if (this.serviceAddress.IsNullOrEmpty())
            {
                var features       = this.server.Features;
                var addressFeature = features?.Get <IServerAddressesFeature>();
                this.serviceAddress = addressFeature?.Addresses?.FirstOrDefault(); // TODO: register all addresses (foreach)
            }

            if (!this.serviceAddress.IsNullOrEmpty())
            {
                // Register this service (use ServiceDescriptor for more infos)
                var uri            = new Uri(this.serviceAddress);
                var registrationId = $"{this.serviceDescriptor.Name}-{HashAlgorithm.ComputeMd5Hash(uri.ToString())}";
                this.logger.LogInformation($"{{LogKey:l}} service registration (id={registrationId}, address={this.serviceAddress})", LogKeys.ServiceDiscovery);

                var registration = new ServiceRegistration
                {
                    Id      = registrationId, // TODO: use resolved servicedescriptor for id/name (AppDomain.CurrentDomain.FriendlyName)
                    Name    = this.serviceDescriptor.Name,
                    Address = $"{uri.Scheme}://{uri.Host}",
                    Port    = uri.Port,
                    Tags    = this.serviceDescriptor.Tags
                };

                //this.logger.LogInformation($"{LogEventIdentifiers.ServiceDiscovery} register (name={{RegistrationName}}, address={registration.FullAddress})", registration.Name);
                this.registryClient.RegisterAsync(registration);
                this.registrationIds.Add(registrationId);
                this.registered = true;
            }
            else
            {
                this.logger.LogWarning("{LogKey:l} service registration failed, missing address", LogKeys.ServiceDiscovery);
            }

            return(Task.CompletedTask);
        }
示例#2
0
        private string EnsureCorrelationId(HttpContext httpContext)
        {
            var isFound = httpContext.Request.Headers.TryGetValue(this.options.CorrelationHeader, out var id);

            if (!isFound || StringValues.IsNullOrEmpty(id))
            {
                if (this.options.UseRandomCorrelationId)
                {
                    //return Guid.NewGuid().ToString(); //.Replace("-", string.Empty);
                    return(IdGenerator.Instance.Next); //RandomGenerator.GenerateString(this.options.RandomCorrelationIdLength, true);
                }
                else if (this.options.UseHashAsCorrelationId)
                {
                    return(HashAlgorithm.ComputeMd5Hash(httpContext.TraceIdentifier));
                }
                else
                {
                    return(httpContext.TraceIdentifier);
                }
            }

            return(id.ToString());
        }
        public static CommandRequestOptions UseAzureServiceBusQueue(
            this CommandRequestOptions options,
            string connectionString = null,
            string name             = "commandrequests",
            TimeSpan?expiration     = null,
            int?retries             = null)
        {
            options.Context.Services.AddSingleton <IQueue <CommandRequestWrapper> >(sp =>
                                                                                    new AzureServiceBusQueue <CommandRequestWrapper>(o => o
                                                                                                                                     .Mediator(sp.GetRequiredService <IMediator>())
                                                                                                                                     .Tracer(sp.GetService <ITracer>())
                                                                                                                                     .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                                                                                                     .ConnectionString(connectionString.EmptyToNull() ?? options.Context.Configuration["naos:commands:azureServiceBusQueue:connectionString"])
                                                                                                                                     .Serializer(new JsonNetSerializer(TypedJsonSerializerSettings.Create())) // needs type information in json to deserialize correctly (which is needed for mediator.send)
                                                                                                                                     .QueueName($"{name}-{HashAlgorithm.ComputeMd5Hash(options.Context.Descriptor.Name)}")
                                                                                                                                     .Expiration(expiration)
                                                                                                                                     .Retries(retries)));

            return(options);
        }
        public static CommandRequestOptions UseAzureBlobStorage(
            this CommandRequestOptions options, string connectionString = null, string containerName = "commandrequests")
        {
            options.Context.Services.AddSingleton(sp => new CommandRequestStore(
                                                      new FileStorageLoggingDecorator(
                                                          sp.GetRequiredService <ILoggerFactory>(),
                                                          new AzureBlobFileStorage(o => o
                                                                                   .ConnectionString(connectionString.EmptyToNull() ?? options.Context.Configuration["naos:commands:azureBlobStorage:connectionString"])
                                                                                   .ContainerName($"{containerName}-{HashAlgorithm.ComputeMd5Hash(options.Context.Descriptor.Name)}")))));

            return(options);
        }