Last active
January 25, 2023 16:16
-
-
Save BenjaminAbt/cf00f2d6a3e06c7be52d71e32521d790 to your computer and use it in GitHub Desktop.
Application Insights MediatR Operation Behavior
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using MediatR; | |
using Microsoft.ApplicationInsights; | |
using Microsoft.ApplicationInsights.DataContracts; | |
using Microsoft.ApplicationInsights.Extensibility; | |
namespace BenjaminAbt.ApplicationInsights.MediatR | |
{ | |
// requiresservices.AddApplicationInsightsTelemetry(); | |
public class ApplicationInsightsBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : notnull | |
{ | |
private readonly TelemetryClient _telemetryClient; | |
public ApplicationInsightsBehavior(TelemetryClient telemetryClient) | |
{ | |
_telemetryClient = telemetryClient; | |
} | |
public async Task<TResponse> Handle( | |
TRequest request, | |
CancellationToken cancellationToken, | |
RequestHandlerDelegate<TResponse> next) | |
{ | |
// use type name as command name | |
string commandName = typeof(TRequest).Name; | |
using IOperationHolder<DependencyTelemetry> operation = _telemetryClient.StartOperation<DependencyTelemetry>(commandName); | |
TResponse response; | |
try | |
{ | |
response = await next().ConfigureAwait(false); | |
operation.Telemetry.Success = true; | |
} | |
catch (Exception e) | |
{ | |
operation.Telemetry.Success = false; | |
_telemetryClient.TrackException(e); | |
throw; | |
} | |
return response; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires
in your DI registration.
Register the Behavior via