namespace Ds.Module.MediatR
{
///
///
///
///
///
public class PerformanceMonitorBehavior : IPipelineBehavior
{
private ILogger> _logger;
public PerformanceMonitorBehavior(ILogger> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken)
{
// 只有在调试模式下才记录,这样就不会在生产环境中加重负担
#if DEBUG
var typeName = typeof(TRequest).Name;
LogPrePerformanceData(typeName);
Stopwatch stopwatch = Stopwatch.StartNew();
try
{
return await next();
}
finally
{
stopwatch.Stop();
LogPostPerformanceData(typeName, stopwatch);
}
#else
return await next();
#endif
}
private void LogPrePerformanceData(string typeName)
{
_logger.LogInformation("----- Handling command {CommandType}", typeName);
}
private void LogPostPerformanceData(string typeName, Stopwatch stopwatch)
{
_logger.LogInformation("----- Done handling command {CommandType} (ElapsedMilliseconds = {ElapsedMilliseconds})", typeName, stopwatch.ElapsedMilliseconds);
}
//使用时需要在Startup.cs中注册
//services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
//services.AddTransient(typeof(IPipelineBehavior<,>), typeof(PerformanceMonitorBehavior<,>));
}
}