Skip to main content

The role of ActivitySource in OpenTelemetry for .NET

While doing some pair programming to integrate OpenTelemetry tracing to a .NET application, we had a discussion on how to use the ActivitySource. It looks simple. You new one up, give it a name, start an activity, done.

The discussion started when we added a second ActivitySource with the exact same name in a different class. This made us wonder: "Are we duplicating traces now? Is this a memory leak? Do we need a singleton?"

So we decided to dig deeper. This post is what we learned…


What ActivitySource actually is

ActivitySource is part of System.Diagnostics, not part of the OpenTelemetry NuGet packages. Microsoft built tracing primitives directly into the BCL, and OpenTelemetry's .NET SDK simply listens to them. This is why you can add distributed tracing to a library without taking a dependency on OpenTelemetry at all.

An ActivitySource is a factory for Activity objects, and an Activity is .NET's name for what OpenTelemetry calls a span.(don’t ask me why decided to use a different name for the same concept) Nothing gets recorded, exported, or even created in memory as a real object unless something is listening.

That "something" is the TracerProviderBuilder configuration in your OpenTelemetry setup.

public static class TelemetryConstants
{
    public const string ServiceName = "OrderProcessing.Api";
}

public class OrderService
{
    private static readonly ActivitySource ActivitySource = new(TelemetryConstants.ServiceName);

    public async Task ProcessOrderAsync(int orderId)
    {
        using var activity = ActivitySource.StartActivity("ProcessOrder");
        activity?.SetTag("order.id", orderId);

        // ... business logic

        activity?.SetStatus(ActivityStatusCode.Ok);
    }
}

And on the OpenTelemetry side:

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing
        .AddSource(TelemetryConstants.ServiceName)
        .AddAspNetCoreInstrumentation()
        .AddOtlpExporter());

That AddSource(...) call is the piece that actually matters. If the name you pass there doesn't match the name of your ActivitySource, your activities are created, populated with tags, disposed... and silently dropped. No error, no warning. This is the number one reason people think "OpenTelemetry isn't working" when actually tracing is working exactly as configured — just not listening to the right name.

The root of our discussion: it's fine to create it more than once

Here's the statement that started the discussion:

"There must be exactly one ActivitySource instance per name in the whole application, otherwise something breaks."

That turns out NOT to be true. You can create as many ActivitySource instances as you want with the same name, in as many classes, assemblies, or NuGet packages as you want. The OpenTelemetry SDK doesn't care about instance identity. It subscribes by name (and optionally version), not by object reference.

// File A
private static readonly ActivitySource Source = new("OrderProcessing.Api");

// File B, completely unrelated class
private static readonly ActivitySource Source = new("OrderProcessing.Api");

Both of these are picked up by the same AddSource("OrderProcessing.Api") call. Activities from either one land in the same trace pipeline, with the same resource attributes. No duplication, no double-exporting, no leak.

Why does this matter in practice?

  • Libraries don't need to expose their internal ActivitySource. A NuGet package can declare its own source with a well-known name, and consumers just call AddSource("ThatLibrary.Name") without ever touching the library's internals.
  • You don't need a shared static class passed around through DI just to get access to one ActivitySource instance. Each component can declare its own, using a shared naming convention (typically the assembly name or a constant).
  • Modular monoliths and Razor Class Libraries can each own their tracing setup without coordinating a single source of truth for the instance itself — only the name needs to be agreed on.

The one thing that does need to line up is the string. Typos are the actual failure mode here, not multiple instantiations.

A wrong-first-attempt

A pattern we noticed in the original codebase: someone tried to be "correct" by injecting ActivitySource through DI as a singleton, because that feels like the safe, testable thing to do.

// Works, but adds ceremony you don't need
services.AddSingleton(new ActivitySource("OrderProcessing.Api"));

public class OrderService(ActivitySource activitySource)
{
    public async Task ProcessOrderAsync(int orderId)
    {
        using var activity = activitySource.StartActivity("ProcessOrder");
        // ...
    }
}

There's nothing broken about this, but it's extra machinery for no real benefit, since ActivitySource instances with the same name are interchangeable anyway. The idiomatic pattern in .NET tracing code and what you'll see in Microsoft's own libraries, is a private static readonly ActivitySource field per class or per assembly, named after the component it belongs to:

internal static class Telemetry
{
    public static readonly ActivitySource Source = new("OrderProcessing.Api.Orders");
}

Simple, no DI registration required, and it works whether the class using it comes from your application, a class library, or a third-party package that adopted the same convention.

Naming and versioning

ActivitySource also accepts an optional version:

private static readonly ActivitySource ActivitySource = new("OrderProcessing.Api.Orders", "1.2.0");

The version travels with the resulting spans as metadata but doesn't affect whether the SDK listens to it — AddSource still matches on name. Use it the same way you'd use assembly versioning: informative for debugging which build produced a trace, not a mechanism for isolation.

A convention worth adopting: name your sources like namespaces (Company.Product.Component), matching how you'd structure logger categories with ILogger<T>. It keeps AddSource calls predictable and makes wildcard matching (AddSource("OrderProcessing.*") in some exporters) actually useful.

Wrapping up

ActivitySource is the entry point into .NET's native tracing story, and OpenTelemetry is just one (very common) listener on top of it. The name is the contract; get that right, register it with AddSource, and you can create as many instances of it as your codebase's structure naturally calls for. Don't let the fear of "duplicate instances" push you into DI ceremony you don't need.

More information

Popular posts from this blog

Podman– Command execution failed with exit code 125

After updating WSL on one of the developer machines, Podman failed to work. When we took a look through Podman Desktop, we noticed that Podman had stopped running and returned the following error message: Error: Command execution failed with exit code 125 Here are the steps we tried to fix the issue: We started by running podman info to get some extra details on what could be wrong: >podman info OS: windows/amd64 provider: wsl version: 5.3.1 Cannot connect to Podman. Please verify your connection to the Linux system using `podman system connection list`, or try `podman machine init` and `podman machine start` to manage a new Linux VM Error: unable to connect to Podman socket: failed to connect: dial tcp 127.0.0.1:2655: connectex: No connection could be made because the target machine actively refused it. That makes sense as the podman VM was not running. Let’s check the VM: >podman machine list NAME         ...

Azure DevOps/ GitHub emoji

I’m really bad at remembering emoji’s. So here is cheat sheet with all emoji’s that can be used in tools that support the github emoji markdown markup: All credits go to rcaviers who created this list.

VS Code Planning mode

After the introduction of Plan mode in Visual Studio , it now also found its way into VS Code. Planning mode, or as I like to call it 'Hannibal mode', extends GitHub Copilot's Agent Mode capabilities to handle larger, multi-step coding tasks with a structured approach. Instead of jumping straight into code generation, Planning mode creates a detailed execution plan. If you want more details, have a look at my previous post . Putting plan mode into action VS Code takes a different approach compared to Visual Studio when using plan mode. Instead of a configuration setting that you can activate but have limited control over, planning is available as a separate chat mode/agent: I like this approach better than how Visual Studio does it as you have explicit control when plan mode is activated. Instead of immediately diving into execution, the plan agent creates a plan and asks some follow up questions: You can further edit the plan by clicking on ‘Open in Editor’: ...