in src/ServiceProfiler.EventPipe.Otel/Azure.Monitor.OpenTelemetry.Profiler/OpenTelemetryBuilderExtensions.cs [61:120]
private static bool IsRegistered(IServiceCollection services) =>
services.Any(descriptor => descriptor.ServiceType == typeof(IServiceProfilerAgentBootstrap));
private static void ConfigureServices(IServiceCollection services, Action<ServiceProfilerOptions>? configureServiceProfiler)
{
services.AddLogging();
services.AddOptions();
services.AddOptions<ServiceProfilerOptions>().Configure<IConfiguration, IOptions<AzureMonitorExporterOptions>>((opt, configuration, azureMonitorOptions) =>
{
configuration.GetSection("ServiceProfiler").Bind(opt);
AzureMonitorExporterOptions? monitorOptions = azureMonitorOptions.Value;
// Inherit connection string from the Azure Monitor Options unless
// the value is already there.
string? azureMonitorConnectionString = monitorOptions.ConnectionString;
if (string.IsNullOrWhiteSpace(opt.ConnectionString))
{
opt.ConnectionString = azureMonitorConnectionString;
}
// Inherit the credential object from the Azure Monitor Options unless
// the value is already there.
opt.Credential ??= monitorOptions.Credential;
configureServiceProfiler?.Invoke(opt);
// Last effort to capture the connection string when all above failed
if (string.IsNullOrEmpty(opt.ConnectionString))
{
opt.ConnectionString = Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING");
}
// Fast fail when the connection string is not set.
// This should never happen, or the profiler is not going to work.
if (string.IsNullOrEmpty(opt.ConnectionString))
{
throw new InvalidOperationException("Connection string can't be fetched. Please follow the instructions to setup connection string properly.");
}
});
services.AddSingleton<IOptions<UserConfigurationBase>>(p =>
{
ServiceProfilerOptions profilerOptions = GetRequiredOptions<ServiceProfilerOptions>(p);
return Options.Create(profilerOptions);
});
services.AddServiceProfilerCore();
services.AddSingleton<IServiceProfilerAgentBootstrap>(p =>
{
ServiceProfilerOptions userConfiguration = GetRequiredOptions<ServiceProfilerOptions>(p);
// Choose one by configurations to register.
return userConfiguration.IsDisabled ?
ActivatorUtilities.CreateInstance<DisabledAgentBootstrap>(p) :
ActivatorUtilities.CreateInstance<ServiceProfilerAgentBootstrap>(p);
});
services.AddHostedService<ProfilerBackgroundService>();
}