-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathHostApplicationBuilderExtensions.cs
More file actions
131 lines (105 loc) · 5.82 KB
/
HostApplicationBuilderExtensions.cs
File metadata and controls
131 lines (105 loc) · 5.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
namespace ServiceControl.Monitoring;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Configuration;
using Hosting;
using Infrastructure;
using Infrastructure.BackgroundTasks;
using Infrastructure.Extensions;
using Licensing;
using Messaging;
using Microsoft.AspNetCore.HttpLogging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Hosting.WindowsServices;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NServiceBus;
using NServiceBus.Configuration.AdvancedExtensibility;
using NServiceBus.Features;
using NServiceBus.Transport;
using QueueLength;
using Timings;
using Transports;
public static class HostApplicationBuilderExtensions
{
public static void AddServiceControlMonitoring(this IHostApplicationBuilder hostBuilder,
Func<ICriticalErrorContext, CancellationToken, Task> onCriticalError, Settings settings,
EndpointConfiguration endpointConfiguration)
{
hostBuilder.Logging.ClearProviders();
hostBuilder.Logging.AddNLog();
hostBuilder.Logging.SetMinimumLevel(settings.LoggingSettings.ToHostLogLevel());
var services = hostBuilder.Services;
var transportSettings = settings.ToTransportSettings();
var transportCustomization = TransportFactory.Create(transportSettings);
transportCustomization.AddTransportForMonitoring(services, transportSettings);
services.Configure<HostOptions>(options => options.ShutdownTimeout = settings.ShutdownTimeout);
if (WindowsServiceHelpers.IsWindowsService())
{
// The if is added for clarity, internally AddWindowsService has a similar logic
hostBuilder.AddWindowsServiceWithRequestTimeout();
}
services.AddSingleton(settings);
services.AddSingleton<EndpointRegistry>();
services.AddSingleton<MessageTypeRegistry>();
services.AddSingleton<EndpointInstanceActivityTracker>();
services.AddSingleton<LegacyQueueLengthReportHandler.LegacyQueueLengthEndpoints>();
services.RegisterAsSelfAndImplementedInterfaces<RetriesStore>();
services.RegisterAsSelfAndImplementedInterfaces<CriticalTimeStore>();
services.RegisterAsSelfAndImplementedInterfaces<ProcessingTimeStore>();
services.RegisterAsSelfAndImplementedInterfaces<QueueLengthStore>();
services.AddSingleton<Action<QueueLengthEntry[], EndpointToQueueMapping>>(provider => (es, q) =>
provider.GetRequiredService<QueueLengthStore>().Store(es.Select(e => ToEntry(e)).ToArray(), ToQueueId(q)));
services.AddHttpLogging(options =>
{
options.LoggingFields = HttpLoggingFields.RequestPath | HttpLoggingFields.RequestMethod | HttpLoggingFields.ResponseStatusCode | HttpLoggingFields.Duration;
});
// Core registers the message dispatcher to be resolved from the transport seam. The dispatcher
// is only available though after the NServiceBus hosted service has started. Any hosted service
// or component injected into a hosted service can only depend on this lazy instead of the dispatcher
// directly and to make things more complex of course the order of registration still matters ;)
services.AddSingleton(provider => new Lazy<IMessageDispatcher>(provider.GetRequiredService<IMessageDispatcher>));
services.AddLicenseCheck();
ConfigureEndpoint(endpointConfiguration, onCriticalError, transportCustomization, transportSettings, settings, services);
hostBuilder.UseNServiceBus(endpointConfiguration);
hostBuilder.AddAsyncTimer();
}
static void ConfigureEndpoint(EndpointConfiguration config, Func<ICriticalErrorContext, CancellationToken, Task> onCriticalError, ITransportCustomization transportCustomization, TransportSettings transportSettings, Settings settings, IServiceCollection services)
{
transportCustomization.CustomizeMonitoringEndpoint(config, transportSettings);
var serviceControlThroughputDataQueue = settings.ServiceControlThroughputDataQueue;
if (!string.IsNullOrWhiteSpace(serviceControlThroughputDataQueue))
{
services.AddHostedService<ReportThroughputHostedService>();
}
services.AddHostedService<RemoveExpiredEndpointInstances>();
config.DefineCriticalErrorAction(onCriticalError);
config.GetSettings().Set(settings);
config.SetDiagnosticsPath(settings.LoggingSettings.LogPath);
if (!transportSettings.MaxConcurrency.HasValue)
{
throw new ArgumentException("MaxConcurrency is not set in TransportSettings");
}
config.LimitMessageProcessingConcurrencyTo(transportSettings.MaxConcurrency.Value);
config.UseSerialization<SystemJsonSerializer>();
config.UsePersistence<NonDurablePersistence>();
var recoverability = config.Recoverability();
recoverability.Immediate(c => c.NumberOfRetries(3));
recoverability.Delayed(c => c.NumberOfRetries(0));
config.SendFailedMessagesTo(transportCustomization.ToTransportQualifiedQueueName(settings.ErrorQueue));
config.DisableFeature<AutoSubscribe>();
config.AddDeserializer<TaggedLongValueWriterOccurrenceSerializerDefinition>();
config.Pipeline.Register(typeof(MessagePoolReleasingBehavior), "Releases pooled message.");
if (AppEnvironment.RunningInContainer)
{
// Do not write diagnostics file
config.CustomDiagnosticsWriter((_, _) => Task.CompletedTask);
}
}
static EndpointInputQueue ToQueueId(EndpointToQueueMapping endpointInputQueueDto) =>
new(endpointInputQueueDto.EndpointName, endpointInputQueueDto.InputQueue);
static RawMessage.Entry ToEntry(QueueLengthEntry entryDto) => new() { DateTicks = entryDto.DateTicks, Value = entryDto.Value };
}