Learn12
Learn12

Reputation: 216

How do I expose HttpContext using ITelemetryInitializer for ApplicationInsights

I'm trying to implement App Insights for an older application using VS 2015 and .NET Framework 4.7.2.

I have a service locator class that builds a ServiceCollection object and then will resolve those classes down the line. Where I need to resolve the service, I don't have access to the HttpContext object.

enter image description here

I read that you can access the AI RequestTelemetry object, which holds many of the same properties HttpContext would, using the ITelemetryInitializer interface. The problem is, when it hits that point in code, the value is NULL.

enter image description here

What I don't understand is how am I supposed to call that Initialize() method to see the RequestTelemetry? Do I pass it another class type that inherits ITelemetryInitializer? I might not be getting the idea of DI down correctly.

Appreciate the help!

Upvotes: 0

Views: 1072

Answers (1)

Peter Bons
Peter Bons

Reputation: 29780

What I don't understand is how am I supposed to call that Initialize() method to see the RequestTelemetry? Do I pass it another class type that inherits ITelemetryInitializer?

You do not have to do anything except adding your initializer to the services collection. App Insights will then execute the Initialize or OnInitializeTelemetry methods of all registered initializers.

Then, regarding the code:

First of all, not al telemetry passing through the initializer will be of type RequestTelemetry. You should instead do something like:

public class CustomInitializer : ITelemetryInitializer
{
    public void Initialize(ITelemetry telemetry)
    {
        if(telemetry is RequestTelemetry requestTelemetry)
        {
            ...
        }
    }
}

In your code requestTelemetry will be null when it is any other type of telemetry like DependencyTelemetry for example.

That said, if you just want to add some properties to / read properties from a specific request you can do

var rt = System.Web.HttpContext.Current.GetRequestTelemetry();
rt.Properties["key"] = "value";

in the controller.

Upvotes: 1

Related Questions