Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dependency injection support #1889

Merged
merged 19 commits into from
Mar 26, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 7 additions & 10 deletions examples/AspNetCore/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using OpenTelemetry;
using OpenTelemetry.Exporter;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

Expand Down Expand Up @@ -63,20 +63,17 @@ public void ConfigureServices(IServiceCollection services)
.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(this.Configuration.GetValue<string>("Jaeger:ServiceName")))
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddJaegerExporter(jaegerOptions =>
{
jaegerOptions.AgentHost = this.Configuration.GetValue<string>("Jaeger:Host");
jaegerOptions.AgentPort = this.Configuration.GetValue<int>("Jaeger:Port");
}));
.AddJaegerExporter());

services.Configure<JaegerExporterOptions>(this.Configuration.GetSection("Jaeger"));
CodeBlanch marked this conversation as resolved.
Show resolved Hide resolved
break;
case "zipkin":
services.AddOpenTelemetryTracing((builder) => builder
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddZipkinExporter(zipkinOptions =>
{
zipkinOptions.Endpoint = new Uri(this.Configuration.GetValue<string>("Zipkin:Endpoint"));
}));
.AddZipkinExporter());

services.Configure<ZipkinExporterOptions>(this.Configuration.GetSection("Zipkin"));
break;
case "otlp":
// Adding the OtlpExporter creates a GrpcChannel.
Expand Down
4 changes: 2 additions & 2 deletions examples/AspNetCore/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
"UseExporter": "console",
"Jaeger": {
"ServiceName": "jaeger-test",
"Host": "localhost",
"Port": 6831
"AgentHost": "localhost",
"AgentPort": 6831
},
"Zipkin": {
"ServiceName": "zipkin-test",
Expand Down
4 changes: 0 additions & 4 deletions src/OpenTelemetry.Api/Trace/TracerProviderBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,6 @@ namespace OpenTelemetry.Trace
/// </summary>
public abstract class TracerProviderBuilder
{
internal TracerProviderBuilder()
{
}

/// <summary>
/// Adds an instrumentation to the provider.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,16 @@ public static TracerProviderBuilder AddJaegerExporter(this TracerProviderBuilder
throw new ArgumentNullException(nameof(builder));
}

var exporterOptions = new JaegerExporterOptions();
JaegerExporterOptions exporterOptions;
if (builder is IResolvingTracerProviderBuilder resolvingTracerProviderBuilder)
CodeBlanch marked this conversation as resolved.
Show resolved Hide resolved
{
exporterOptions = resolvingTracerProviderBuilder.ResolveOptions<JaegerExporterOptions>();
}
else
{
exporterOptions = new JaegerExporterOptions();
}

configure?.Invoke(exporterOptions);
var jaegerExporter = new JaegerExporter(exporterOptions);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,16 @@ public static TracerProviderBuilder AddZipkinExporter(this TracerProviderBuilder
throw new ArgumentNullException(nameof(builder));
}

var exporterOptions = new ZipkinExporterOptions();
ZipkinExporterOptions exporterOptions;
if (builder is IResolvingTracerProviderBuilder resolvingTracerProviderBuilder)
{
exporterOptions = resolvingTracerProviderBuilder.ResolveOptions<ZipkinExporterOptions>();
}
else
{
exporterOptions = new ZipkinExporterOptions();
}

configure?.Invoke(exporterOptions);
var zipkinExporter = new ZipkinExporter(exporterOptions);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// <copyright file="TracerProviderBuilderHosting.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System;
using System.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace OpenTelemetry.Trace
{
internal class TracerProviderBuilderHosting : TracerProviderBuilderSdk, IResolvingTracerProviderBuilder
{
private readonly IServiceProvider serviceProvider;

public TracerProviderBuilderHosting(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
}

public TracerProviderBuilder AddInstrumentation<T>()
where T : class
{
return this.AddInstrumentation(() => this.ResolveService<T>());
}

public TracerProviderBuilder AddProcessor<T>()
where T : BaseProcessor<Activity>
{
return this.AddProcessor(this.serviceProvider.GetRequiredService<T>());
}

public TracerProviderBuilder SetSampler<T>()
where T : Sampler
{
return this.SetSampler(this.serviceProvider.GetRequiredService<T>());
}

public T ResolveService<T>()
{
return this.serviceProvider.GetRequiredService<T>();
}

public T ResolveOptions<T>()
where T : class, new()
{
return this.serviceProvider.GetRequiredService<IOptions<T>>().Value;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@
// </copyright>

using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using OpenTelemetry;
using OpenTelemetry.Extensions.Hosting.Implementation;
using OpenTelemetry.Trace;

Expand All @@ -35,8 +35,7 @@ public static class OpenTelemetryServicesExtensions
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddOpenTelemetryTracing(this IServiceCollection services)
{
services.AddOpenTelemetryTracing(builder => { });
return services;
return services.AddOpenTelemetryTracing((sp, builder) => { });
}

/// <summary>
Expand All @@ -52,10 +51,7 @@ public static IServiceCollection AddOpenTelemetryTracing(this IServiceCollection
throw new ArgumentNullException(nameof(configure));
}

var builder = Sdk.CreateTracerProviderBuilder();
configure(builder);
services.AddOpenTelemetryTracing(() => builder.Build());
return services;
return services.AddOpenTelemetryTracing((sp, builder) => { configure(builder); });
}

/// <summary>
Expand All @@ -71,44 +67,33 @@ public static IServiceCollection AddOpenTelemetryTracing(this IServiceCollection
throw new ArgumentNullException(nameof(configure));
}

var builder = Sdk.CreateTracerProviderBuilder();
services.AddOpenTelemetryTracing((sp) =>
return services.AddOpenTelemetryTracing(sp =>
{
var builder = new TracerProviderBuilderHosting(sp);

var tracerProviderBuilderConfigurationCallbacks = sp.GetService<IEnumerable<TracerProviderBuilderConfigurationCallback>>();
if (tracerProviderBuilderConfigurationCallbacks != null)
{
foreach (var tracerProviderBuilderConfigurationCallback in tracerProviderBuilderConfigurationCallbacks)
{
tracerProviderBuilderConfigurationCallback.Configure(sp, builder);
}
}

configure(sp, builder);
return builder.Build();
});
return services;
}

/// <summary>
/// Adds OpenTelemetry TracerProvider to the specified <see cref="IServiceCollection" />.
/// Register a callback to be called during the configuration of the OpenTelemetry <see cref="TracerProviderBuilder"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="createTracerProvider">A delegate that provides the tracer provider to be registered.</param>
/// <param name="services"><see cref="IServiceCollection"/>.</param>
/// <param name="configure">Configuration callback action.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
private static IServiceCollection AddOpenTelemetryTracing(this IServiceCollection services, Func<TracerProvider> createTracerProvider)
public static IServiceCollection ConfigureOpenTelemetryTracing(this IServiceCollection services, Action<IServiceProvider, TracerProviderBuilder> configure)
{
if (services is null)
{
throw new ArgumentNullException(nameof(services));
}

if (createTracerProvider is null)
{
throw new ArgumentNullException(nameof(createTracerProvider));
}

try
{
services.AddSingleton(s => createTracerProvider());
AddOpenTelemetryTracingInternal(services);
}
catch (Exception ex)
{
HostingExtensionsEventSource.Log.FailedInitialize(ex);
}

return services;
return services.AddSingleton(new TracerProviderBuilderConfigurationCallback { Configure = configure });
}

/// <summary>
Expand All @@ -131,8 +116,9 @@ private static IServiceCollection AddOpenTelemetryTracing(this IServiceCollectio

try
{
services.AddSingleton(s => createTracerProvider(s));
AddOpenTelemetryTracingInternal(services);
return services
.AddSingleton(s => createTracerProvider(s))
.AddOpenTelemetryTracingInternal();
}
catch (Exception ex)
{
Expand All @@ -142,9 +128,15 @@ private static IServiceCollection AddOpenTelemetryTracing(this IServiceCollectio
return services;
}

private static void AddOpenTelemetryTracingInternal(IServiceCollection services)
private static IServiceCollection AddOpenTelemetryTracingInternal(this IServiceCollection services)
{
services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, TelemetryHostedService>());
return services;
}

private class TracerProviderBuilderConfigurationCallback
{
public Action<IServiceProvider, TracerProviderBuilder> Configure { get; set; }
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// <copyright file="TracerProviderBuilderExtensions.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System.Diagnostics;

namespace OpenTelemetry.Trace
{
public static class TracerProviderBuilderExtensions
{
public static TracerProviderBuilder AddInstrumentation<T>(this TracerProviderBuilder tracerProviderBuilder)
where T : class
{
if (tracerProviderBuilder is TracerProviderBuilderHosting tracerProviderBuilderHosting)
{
tracerProviderBuilderHosting.AddInstrumentation<T>();
}

return tracerProviderBuilder;
}

public static TracerProviderBuilder AddProcessor<T>(this TracerProviderBuilder tracerProviderBuilder)
where T : BaseProcessor<Activity>
{
if (tracerProviderBuilder is TracerProviderBuilderHosting tracerProviderBuilderHosting)
{
tracerProviderBuilderHosting.AddProcessor<T>();
}

return tracerProviderBuilder;
}

public static TracerProviderBuilder SetSampler<T>(this TracerProviderBuilder tracerProviderBuilder)
where T : Sampler
{
if (tracerProviderBuilder is TracerProviderBuilderHosting tracerProviderBuilderHosting)
{
tracerProviderBuilderHosting.SetSampler<T>();
}

return tracerProviderBuilder;
}
}
}
26 changes: 26 additions & 0 deletions src/OpenTelemetry/Trace/IResolvingTracerProviderBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// <copyright file="IResolvingTracerProviderBuilder.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

namespace OpenTelemetry.Trace
{
public interface IResolvingTracerProviderBuilder
CodeBlanch marked this conversation as resolved.
Show resolved Hide resolved
{
T ResolveService<T>();

T ResolveOptions<T>()
where T : class, new();
}
}
6 changes: 1 addition & 5 deletions src/OpenTelemetry/Trace/TracerProviderBuilderSdk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ namespace OpenTelemetry.Trace
/// <summary>
/// Build TracerProvider with Resource, Sampler, Processors and Instrumentation.
/// </summary>
internal class TracerProviderBuilderSdk : TracerProviderBuilder
public class TracerProviderBuilderSdk : TracerProviderBuilder
CodeBlanch marked this conversation as resolved.
Show resolved Hide resolved
{
private readonly List<InstrumentationFactory> instrumentationFactories = new List<InstrumentationFactory>();
private readonly List<BaseProcessor<Activity>> processors = new List<BaseProcessor<Activity>>();
Expand All @@ -33,10 +33,6 @@ internal class TracerProviderBuilderSdk : TracerProviderBuilder
private ResourceBuilder resourceBuilder = ResourceBuilder.CreateDefault();
private Sampler sampler = new ParentBasedSampler(new AlwaysOnSampler());

internal TracerProviderBuilderSdk()
{
}

/// <summary>
/// Adds an instrumentation to the provider.
/// </summary>
Expand Down