11using System . Diagnostics ;
22using System . Reflection ;
33using Ardalis . GuardClauses ;
4- using MediatR ;
4+ using Mediator ;
55using Microsoft . Extensions . Logging ;
66
77namespace Ardalis . SharedKernel ;
88
99/// <summary>
10- /// Adds logging for all requests in MediatR pipeline.
10+ /// Adds logging for all requests in Mediator pipeline.
1111/// Configure by adding the service with a scoped lifetime
12- ///
13- /// Example for Autofac:
14- /// builder
15- /// .RegisterType<Mediator>()
16- /// .As<IMediator>()
17- /// .InstancePerLifetimeScope();
18- ///
19- /// builder
20- /// .RegisterGeneric(typeof(LoggingBehavior<,>))
21- /// .As(typeof(IPipelineBehavior<,>))
22- /// .InstancePerLifetimeScope();
23- ///
2412/// </summary>
2513/// <typeparam name="TRequest"></typeparam>
2614/// <typeparam name="TResponse"></typeparam>
27- public class LoggingBehavior < TRequest , TResponse > : IPipelineBehavior < TRequest , TResponse >
28- where TRequest : IRequest < TResponse >
15+ public class LoggingBehavior < TRequest , TResponse > ( ILogger < LoggingBehavior < TRequest , TResponse > > logger )
16+ : IPipelineBehavior < TRequest , TResponse >
17+ where TRequest : IRequest < TResponse >
2918{
30- private readonly ILogger < Mediator > _logger ;
19+ private readonly ILogger < LoggingBehavior < TRequest , TResponse > > _logger = logger ;
3120
32- public LoggingBehavior ( ILogger < Mediator > logger )
33- {
34- _logger = logger ;
35- }
36-
37- public async Task < TResponse > Handle ( TRequest request , RequestHandlerDelegate < TResponse > next , CancellationToken cancellationToken )
21+ public async ValueTask < TResponse > Handle (
22+ TRequest request ,
23+ MessageHandlerDelegate < TRequest , TResponse > next ,
24+ CancellationToken cancellationToken )
3825 {
3926 Guard . Against . Null ( request ) ;
4027 if ( _logger . IsEnabled ( LogLevel . Information ) )
4128 {
4229 _logger . LogInformation ( "Handling {RequestName}" , typeof ( TRequest ) . Name ) ;
4330
44- // Reflection! Could be a performance concern
4531 Type myType = request . GetType ( ) ;
4632 IList < PropertyInfo > props = new List < PropertyInfo > ( myType . GetProperties ( ) ) ;
4733 foreach ( PropertyInfo prop in props )
@@ -53,11 +39,10 @@ public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TRe
5339
5440 var sw = Stopwatch . StartNew ( ) ;
5541
56- var response = await next ( ) ;
42+ var response = await next ( request , cancellationToken ) ;
5743
5844 _logger . LogInformation ( "Handled {RequestName} with {Response} in {ms} ms" , typeof ( TRequest ) . Name , response , sw . ElapsedMilliseconds ) ;
5945 sw . Stop ( ) ;
6046 return response ;
6147 }
6248}
63-
0 commit comments