Skip to content

Instantly share code, notes, and snippets.

@BenjaminAbt
Last active January 25, 2023 16:16
Show Gist options
  • Save BenjaminAbt/cf00f2d6a3e06c7be52d71e32521d790 to your computer and use it in GitHub Desktop.
Save BenjaminAbt/cf00f2d6a3e06c7be52d71e32521d790 to your computer and use it in GitHub Desktop.
Application Insights MediatR Operation Behavior
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;
}
}
}
@BenjaminAbt
Copy link
Author

Requires

services.AddApplicationInsightsTelemetry();

in your DI registration.

Register the Behavior via

services.AddMediatR();
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ApplicationInsightsBehavior<,>));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment