dotnet / dotnet/docs

Unexpected 'TypeInitializationException' when following ActivitySource Best Practices

Open
#42,745 0 comments 0 reactions 0 assignees View on GitHub
:watch: Not Triaged dotnet-fundamentals/svc
Dominant language
No language data
Stars
4.8k
Forks
6.1k
Avg merge
15h 21m
Merged PRs (30d)
370

Description

### Type of issue

Missing information

### Description

The current documentation under **Best Practices** states:

> Create the ActivitySource once, store it in a static variable and use that instance as long as needed.

However, following this recommendation can potentially cause an unexpected `System.TypeInitializationException` when using custom activity listeners. This behavior is not immediately clear from the documentation and might impact users implementing such listeners.

#### Proposed Solution

It would be helpful to add a note or warning to the documentation about this potential exception and provide guidance on how to handle or avoid it when using `ActivitySource` in static fields, especially in scenarios involving custom activity listeners.

#### Steps to Reproduce

```csharp
[TestFixture]
public class DiagnosticsTests_StrangerThings
{
private static class Telemetry
{
public static ActivitySource MyActivitySource { get; } = new ActivitySource("MyActivitySource");
}

[Test]
public void Test()
{
ActivitySource.AddActivityListener(new ActivityListener
{
ShouldListenTo = newActivitySource =>
{
var myActivitySource = Telemetry.MyActivitySource;

// System.TypeInitializationException : The type initializer for 'Telemetry' threw an exception.
// ----> System.NullReferenceException : Object reference not set to an instance of an object.
// at Test.DiagnosticsTests_Strange1.Telemetry.get_MyActivitySource()
return newActivitySource.Name == myActivitySource.Name;
},
Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllData,
});

var activity = new ActivitySource("OtherActivitySource").StartActivity();

Assert.That(activity, Is.Null);
}
}
```

### Page URL

https://learn.microsoft.com/en-us/dotnet/core/diagnostics/distributed-tracing-instrumentation-walkthroughs

### Content source URL

https://github.com/dotnet/docs/blob/main/docs/core/diagnostics/distributed-tracing-instrumentation-walkthroughs.md

### Document Version Independent Id

dc4689df-b03a-e744-dbed-f23d8defcb6e

### Article author

@tommcdon

### Metadata

* ID: 3f30f3b0-90cb-d2eb-ee08-4319ffcb7686
* Service: **dotnet-fundamentals**

[Related Issues](https://github.com/dotnet/docs/issues?q=is%3Aissue+is%3Aopen+dc4689df-b03a-e744-dbed-f23d8defcb6e)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.