From 57db50d14e2530449e4c117c8056caefe8791826 Mon Sep 17 00:00:00 2001 From: Martin Othamar Date: Mon, 25 Apr 2022 17:50:47 +0200 Subject: [PATCH] Add csharpier for consistent formatting (#31) --- .csharpierrc.json | 3 + Build.csproj | 9 +- Directory.Build.props | 7 + Mediator.sln | 2 + .../Notification/NotificationBenchmarks.cs | 61 ++-- .../Request/RequestBenchmarks.cs | 54 +-- .../Request/StreamingBenchmarks.cs | 33 +- .../Request/StructRequestBenchmarks.cs | 61 ++-- .../Controllers/WeatherForecastController.cs | 1 - samples/ASPNET/Program.cs | 1 + .../WeatherForecasts/GetWeatherForecasts.cs | 35 +- .../WeatherForecasts/WeatherForecast.cs | 2 +- .../AspNetSample.Api/Program.cs | 22 +- .../AspNetSample.Api/Startup.cs | 20 +- .../Pipeline/ErrorLoggingBehaviour.cs | 8 +- .../Pipeline/MessageValidatorBehaviour.cs | 8 +- .../Todos/TodoItemQueryHandler.cs | 4 +- .../ValidationException.cs | 3 +- samples/SimpleConsole/Program.cs | 26 +- samples/SimpleConsoleAOT/Program.cs | 14 +- samples/SimpleEndToEnd/Program.cs | 17 +- samples/SimpleStreaming/Program.cs | 5 +- samples/WPFApp/MainWindow.xaml.cs | 34 +- samples/WPFApp/Properties/AssemblyInfo.cs | 10 +- .../Analysis/CompilationAnalyzer.cs | 337 ++++++++++++------ .../Analysis/InvocationSyntaxReceiver.cs | 5 +- .../Analysis/MessageHandler.cs | 5 +- .../Analysis/NotificationMessage.cs | 12 +- .../Analysis/NotificationMessageHandler.cs | 9 +- .../Analysis/RequestMessage.cs | 31 +- .../Analysis/RequestMessageHandlerWrapper.cs | 38 +- .../Analysis/SymbolMetadata.cs | 3 +- .../Diagnostics.cs | 77 ++-- .../EmbeddedResource.cs | 17 +- .../Extensions/IsExternalInit.cs | 4 +- .../Extensions/RoslynExtensions.cs | 24 +- .../MediatorGenerationContext.cs | 6 +- .../MediatorGenerator.cs | 5 +- .../IncrementalMediatorGenerator.cs | 24 +- src/Mediator/Handlers/ICommandHandler.cs | 8 +- src/Mediator/Handlers/INotificationHandler.cs | 3 +- src/Mediator/Handlers/IQueryHandler.cs | 3 +- src/Mediator/Handlers/IRequestHandler.cs | 8 +- .../Handlers/IStreamCommandHandler.cs | 3 +- src/Mediator/Handlers/IStreamQueryHandler.cs | 3 +- .../Handlers/IStreamRequestHandler.cs | 3 +- src/Mediator/IMediator.cs | 4 +- src/Mediator/ISender.cs | 19 +- src/Mediator/Pipeline/IPipelineBehavior.cs | 9 +- .../Pipeline/IStreamPipelineBehavior.cs | 9 +- .../Pipeline/MessageHandlerDelegate.cs | 6 +- .../Pipeline/StreamHandlerDelegate.cs | 6 +- .../NonParallelCollectionDefinitionClass.cs | 4 +- .../RequestTests.cs | 29 +- .../SomeNotificationMemAllocTracking.cs | 3 +- test/Mediator.SmokeTestConsole/Program.cs | 62 ++-- .../AssertExtensions.cs | 6 +- .../Assertions.cs | 6 +- .../Fixture.cs | 12 +- .../GeneratorResult.cs | 7 +- .../LifetimeOptionTests.cs | 6 +- .../ReportingTests.cs | 30 +- .../SamplesTests.cs | 15 +- .../SourceGenVerifier.cs | 55 +-- .../resources/ConfigurationConflictProgram.cs | 12 +- .../resources/ConstVariablesConfig.cs | 12 +- .../resources/IntCastLifetime.cs | 10 +- .../resources/InvalidVariablesConfig.cs | 12 +- .../resources/LocalLiteralVariableConfig.cs | 12 +- .../LocalVariablesReferencingConstsConfig.cs | 12 +- .../resources/NullNamespaceVariable.cs | 10 +- .../resources/StreamingProgram.cs | 5 +- .../UnassignedLifetimeVariableConfig.cs | 10 +- .../UnassignedNamespaceVariableConfig.cs | 10 +- .../resources/UnassignedVariablesConfig.cs | 12 +- test/Mediator.Tests.ScopedLifetime/Init.cs | 3 +- test/Mediator.Tests.ScopedLifetime/Options.cs | 1 - .../Options.cs | 1 - .../AbstractRequestHandlerTests.cs | 15 +- test/Mediator.Tests/BasicHandlerTests.cs | 3 +- test/Mediator.Tests/Fixture.cs | 22 +- .../NonParallelCollectionDefinitionClass.cs | 4 +- .../OpenConstrainedGenericsTests.cs | 40 ++- .../Pipeline/CommandSpecificPipeline.cs | 9 +- .../Pipeline/GenericPipeline.cs | 33 +- test/Mediator.Tests/Pipeline/PipelineTests.cs | 50 +-- test/Mediator.Tests/Pipeline/SomePipeline.cs | 6 +- .../Pipeline/StreamingPipelineTests.cs | 25 +- .../Mediator.Tests/RequestInheritanceTests.cs | 6 +- test/Mediator.Tests/StreamingTests.cs | 8 +- test/Mediator.Tests/StructResponseTests.cs | 11 +- test/Mediator.Tests/TestTypes/SomeCommand.cs | 1 + .../TestTypes/SomeQueryHandler.cs | 3 +- .../TestTypes/SomeRequestHandler.cs | 8 +- .../TestTypes/SomeStreamingCommand.cs | 5 +- .../TestTypes/SomeStreamingCommandStruct.cs | 5 +- .../TestTypes/SomeStreamingQuery.cs | 5 +- .../TestTypes/SomeStreamingRequest.cs | 5 +- 98 files changed, 1084 insertions(+), 658 deletions(-) create mode 100644 .csharpierrc.json diff --git a/.csharpierrc.json b/.csharpierrc.json new file mode 100644 index 0000000..6a457af --- /dev/null +++ b/.csharpierrc.json @@ -0,0 +1,3 @@ +{ + "printWidth": 120 +} diff --git a/Build.csproj b/Build.csproj index f62b34d..826c787 100644 --- a/Build.csproj +++ b/Build.csproj @@ -1,11 +1,6 @@ - - - - - - - + + diff --git a/Directory.Build.props b/Directory.Build.props index 157dc52..2105571 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -22,4 +22,11 @@ 6.0.0 + + + + all + runtime; build; native; contentfiles; analyzers + + diff --git a/Mediator.sln b/Mediator.sln index bc99b72..6333a66 100644 --- a/Mediator.sln +++ b/Mediator.sln @@ -57,6 +57,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_files", "_files", "{FDAEEF NuGet.config = NuGet.config README.md = README.md version.json = version.json + .csharpierrc.json = .csharpierrc.json + Build.csproj = Build.csproj EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mediator.Tests.TransientLifetime", "test\Mediator.Tests.TransientLifetime\Mediator.Tests.TransientLifetime.csproj", "{4C18FD08-BCE4-4C6A-9D84-9A81C4561586}" diff --git a/benchmarks/Mediator.Benchmarks/Notification/NotificationBenchmarks.cs b/benchmarks/Mediator.Benchmarks/Notification/NotificationBenchmarks.cs index 8213bd5..88a181b 100644 --- a/benchmarks/Mediator.Benchmarks/Notification/NotificationBenchmarks.cs +++ b/benchmarks/Mediator.Benchmarks/Notification/NotificationBenchmarks.cs @@ -8,19 +8,19 @@ namespace Mediator.Benchmarks.Notification; public sealed record SomeNotification(Guid Id) : INotification, MediatR.INotification; -public sealed class SomeHandlerClass : - INotificationHandler, - MediatR.INotificationHandler, - IAsyncMessageHandler +public sealed class SomeHandlerClass + : INotificationHandler, + MediatR.INotificationHandler, + IAsyncMessageHandler { - public ValueTask Handle(SomeNotification notification, CancellationToken cancellationToken) => - default; + public ValueTask Handle(SomeNotification notification, CancellationToken cancellationToken) => default; - public ValueTask HandleAsync(SomeNotification message, CancellationToken cancellationToken) => - default; + public ValueTask HandleAsync(SomeNotification message, CancellationToken cancellationToken) => default; - Task MediatR.INotificationHandler.Handle(SomeNotification notification, CancellationToken cancellationToken) => - Task.CompletedTask; + Task MediatR.INotificationHandler.Handle( + SomeNotification notification, + CancellationToken cancellationToken + ) => Task.CompletedTask; } [MemoryDiagnoser] @@ -50,26 +50,31 @@ public void Setup() { var services = new ServiceCollection(); services.AddMediator(opts => opts.ServiceLifetime = ServiceLifetime); - services.AddMediatR(opts => - { - _ = ServiceLifetime switch + services.AddMediatR( + opts => { - ServiceLifetime.Singleton => opts.AsSingleton(), - ServiceLifetime.Scoped => opts.AsScoped(), - ServiceLifetime.Transient => opts.AsTransient(), - _ => throw new InvalidOperationException(), - }; - }, typeof(SomeHandlerClass).Assembly); - services.AddMessagePipe(opts => - { - opts.InstanceLifetime = ServiceLifetime switch + _ = ServiceLifetime switch + { + ServiceLifetime.Singleton => opts.AsSingleton(), + ServiceLifetime.Scoped => opts.AsScoped(), + ServiceLifetime.Transient => opts.AsTransient(), + _ => throw new InvalidOperationException(), + }; + }, + typeof(SomeHandlerClass).Assembly + ); + services.AddMessagePipe( + opts => { - ServiceLifetime.Singleton => InstanceLifetime.Singleton, - ServiceLifetime.Scoped => InstanceLifetime.Scoped, - ServiceLifetime.Transient => InstanceLifetime.Transient, - _ => throw new InvalidOperationException(), - }; - }); + opts.InstanceLifetime = ServiceLifetime switch + { + ServiceLifetime.Singleton => InstanceLifetime.Singleton, + ServiceLifetime.Scoped => InstanceLifetime.Scoped, + ServiceLifetime.Transient => InstanceLifetime.Transient, + _ => throw new InvalidOperationException(), + }; + } + ); _serviceProvider = services.BuildServiceProvider(); if (ServiceLifetime == ServiceLifetime.Scoped) diff --git a/benchmarks/Mediator.Benchmarks/Request/RequestBenchmarks.cs b/benchmarks/Mediator.Benchmarks/Request/RequestBenchmarks.cs index 1ff3132..b21ca77 100644 --- a/benchmarks/Mediator.Benchmarks/Request/RequestBenchmarks.cs +++ b/benchmarks/Mediator.Benchmarks/Request/RequestBenchmarks.cs @@ -10,10 +10,10 @@ public sealed record SomeRequest(Guid Id) : IRequest, MediatR.IReq public sealed record SomeResponse(Guid Id); -public sealed class SomeHandlerClass : - IRequestHandler, - MediatR.IRequestHandler, - IAsyncRequestHandler +public sealed class SomeHandlerClass + : IRequestHandler, + MediatR.IRequestHandler, + IAsyncRequestHandler { private static readonly SomeResponse _response = new SomeResponse(Guid.NewGuid()); @@ -22,7 +22,10 @@ public sealed class SomeHandlerClass : public ValueTask Handle(SomeRequest request, CancellationToken cancellationToken) => _vtResponse; - Task MediatR.IRequestHandler.Handle(SomeRequest request, CancellationToken cancellationToken) => _tResponse; + Task MediatR.IRequestHandler.Handle( + SomeRequest request, + CancellationToken cancellationToken + ) => _tResponse; public ValueTask InvokeAsync(SomeRequest request, CancellationToken cancellationToken) => _vtResponse; } @@ -52,26 +55,31 @@ public void Setup() { var services = new ServiceCollection(); services.AddMediator(opts => opts.ServiceLifetime = ServiceLifetime); - services.AddMediatR(opts => - { - _ = ServiceLifetime switch + services.AddMediatR( + opts => { - ServiceLifetime.Singleton => opts.AsSingleton(), - ServiceLifetime.Scoped => opts.AsScoped(), - ServiceLifetime.Transient => opts.AsTransient(), - _ => throw new InvalidOperationException(), - }; - }, typeof(SomeHandlerClass).Assembly); - services.AddMessagePipe(opts => - { - opts.InstanceLifetime = ServiceLifetime switch + _ = ServiceLifetime switch + { + ServiceLifetime.Singleton => opts.AsSingleton(), + ServiceLifetime.Scoped => opts.AsScoped(), + ServiceLifetime.Transient => opts.AsTransient(), + _ => throw new InvalidOperationException(), + }; + }, + typeof(SomeHandlerClass).Assembly + ); + services.AddMessagePipe( + opts => { - ServiceLifetime.Singleton => InstanceLifetime.Singleton, - ServiceLifetime.Scoped => InstanceLifetime.Scoped, - ServiceLifetime.Transient => InstanceLifetime.Transient, - _ => throw new InvalidOperationException(), - }; - }); + opts.InstanceLifetime = ServiceLifetime switch + { + ServiceLifetime.Singleton => InstanceLifetime.Singleton, + ServiceLifetime.Scoped => InstanceLifetime.Scoped, + ServiceLifetime.Transient => InstanceLifetime.Transient, + _ => throw new InvalidOperationException(), + }; + } + ); _serviceProvider = services.BuildServiceProvider(); if (ServiceLifetime == ServiceLifetime.Scoped) diff --git a/benchmarks/Mediator.Benchmarks/Request/StreamingBenchmarks.cs b/benchmarks/Mediator.Benchmarks/Request/StreamingBenchmarks.cs index 35dff1a..952de0d 100644 --- a/benchmarks/Mediator.Benchmarks/Request/StreamingBenchmarks.cs +++ b/benchmarks/Mediator.Benchmarks/Request/StreamingBenchmarks.cs @@ -7,9 +7,9 @@ namespace Mediator.Benchmarks.Request; public sealed record SomeStreamRequest(Guid Id) : IStreamRequest, MediatR.IStreamRequest; -public sealed class SomeStreamHandlerClass : - IStreamRequestHandler, - MediatR.IStreamRequestHandler +public sealed class SomeStreamHandlerClass + : IStreamRequestHandler, + MediatR.IStreamRequestHandler { private static readonly SomeResponse _response = new SomeResponse(Guid.NewGuid()); @@ -26,8 +26,10 @@ async IAsyncEnumerable _enumerate() public IAsyncEnumerable Handle(SomeStreamRequest request, CancellationToken cancellationToken) => _enumerate(); - IAsyncEnumerable MediatR.IStreamRequestHandler.Handle(SomeStreamRequest request, CancellationToken cancellationToken) => - _enumerate(); + IAsyncEnumerable MediatR.IStreamRequestHandler.Handle( + SomeStreamRequest request, + CancellationToken cancellationToken + ) => _enumerate(); } [MemoryDiagnoser] @@ -54,16 +56,19 @@ public void Setup() { var services = new ServiceCollection(); services.AddMediator(opts => opts.ServiceLifetime = ServiceLifetime); - services.AddMediatR(opts => - { - _ = ServiceLifetime switch + services.AddMediatR( + opts => { - ServiceLifetime.Singleton => opts.AsSingleton(), - ServiceLifetime.Scoped => opts.AsScoped(), - ServiceLifetime.Transient => opts.AsTransient(), - _ => throw new InvalidOperationException(), - }; - }, typeof(SomeHandlerClass).Assembly); + _ = ServiceLifetime switch + { + ServiceLifetime.Singleton => opts.AsSingleton(), + ServiceLifetime.Scoped => opts.AsScoped(), + ServiceLifetime.Transient => opts.AsTransient(), + _ => throw new InvalidOperationException(), + }; + }, + typeof(SomeHandlerClass).Assembly + ); _serviceProvider = services.BuildServiceProvider(); if (ServiceLifetime == ServiceLifetime.Scoped) diff --git a/benchmarks/Mediator.Benchmarks/Request/StructRequestBenchmarks.cs b/benchmarks/Mediator.Benchmarks/Request/StructRequestBenchmarks.cs index 273a35c..38c3c94 100644 --- a/benchmarks/Mediator.Benchmarks/Request/StructRequestBenchmarks.cs +++ b/benchmarks/Mediator.Benchmarks/Request/StructRequestBenchmarks.cs @@ -24,18 +24,26 @@ public SomeStructRequest(Guid id) } } -public sealed class SomeStructHandler : IRequestHandler, MediatR.IRequestHandler, IAsyncRequestHandler +public sealed class SomeStructHandler + : IRequestHandler, + MediatR.IRequestHandler, + IAsyncRequestHandler { private static readonly SomeResponse _response = new SomeResponse(Guid.NewGuid()); private static readonly Task _tResponse = Task.FromResult(_response); private static ValueTask _vtResponse => new ValueTask(_response); - public ValueTask Handle(SomeStructRequest request, CancellationToken cancellationToken) => _vtResponse; + public ValueTask Handle(SomeStructRequest request, CancellationToken cancellationToken) => + _vtResponse; - Task MediatR.IRequestHandler.Handle(SomeStructRequest request, CancellationToken cancellationToken) => _tResponse; + Task MediatR.IRequestHandler.Handle( + SomeStructRequest request, + CancellationToken cancellationToken + ) => _tResponse; - public ValueTask InvokeAsync(SomeStructRequest request, CancellationToken cancellationToken) => _vtResponse; + public ValueTask InvokeAsync(SomeStructRequest request, CancellationToken cancellationToken) => + _vtResponse; } [MemoryDiagnoser] @@ -63,26 +71,31 @@ public void Setup() { var services = new ServiceCollection(); services.AddMediator(opts => opts.ServiceLifetime = ServiceLifetime); - services.AddMediatR(opts => - { - _ = ServiceLifetime switch + services.AddMediatR( + opts => { - ServiceLifetime.Singleton => opts.AsSingleton(), - ServiceLifetime.Scoped => opts.AsScoped(), - ServiceLifetime.Transient => opts.AsTransient(), - _ => throw new InvalidOperationException(), - }; - }, typeof(SomeHandlerClass).Assembly); - services.AddMessagePipe(opts => - { - opts.InstanceLifetime = ServiceLifetime switch + _ = ServiceLifetime switch + { + ServiceLifetime.Singleton => opts.AsSingleton(), + ServiceLifetime.Scoped => opts.AsScoped(), + ServiceLifetime.Transient => opts.AsTransient(), + _ => throw new InvalidOperationException(), + }; + }, + typeof(SomeHandlerClass).Assembly + ); + services.AddMessagePipe( + opts => { - ServiceLifetime.Singleton => InstanceLifetime.Singleton, - ServiceLifetime.Scoped => InstanceLifetime.Scoped, - ServiceLifetime.Transient => InstanceLifetime.Transient, - _ => throw new InvalidOperationException(), - }; - }); + opts.InstanceLifetime = ServiceLifetime switch + { + ServiceLifetime.Singleton => InstanceLifetime.Singleton, + ServiceLifetime.Scoped => InstanceLifetime.Scoped, + ServiceLifetime.Transient => InstanceLifetime.Transient, + _ => throw new InvalidOperationException(), + }; + } + ); _serviceProvider = services.BuildServiceProvider(); if (ServiceLifetime == ServiceLifetime.Scoped) @@ -96,7 +109,9 @@ public void Setup() _mediator = _serviceProvider.GetRequiredService(); _concreteMediator = _serviceProvider.GetRequiredService(); _mediatr = _serviceProvider.GetRequiredService(); - _messagePipeHandler = _serviceProvider.GetRequiredService>(); + _messagePipeHandler = _serviceProvider.GetRequiredService< + IAsyncRequestHandler + >(); _handler = _serviceProvider.GetRequiredService(); _request = new(Guid.NewGuid()); } diff --git a/samples/ASPNET/Controllers/WeatherForecastController.cs b/samples/ASPNET/Controllers/WeatherForecastController.cs index d7b5961..759aa98 100644 --- a/samples/ASPNET/Controllers/WeatherForecastController.cs +++ b/samples/ASPNET/Controllers/WeatherForecastController.cs @@ -8,7 +8,6 @@ namespace ASPNET.Controllers [Route("[controller]")] public class WeatherForecastController : ControllerBase { - private readonly ILogger _logger; private readonly IMediator _mediator; diff --git a/samples/ASPNET/Program.cs b/samples/ASPNET/Program.cs index f017f47..97c6b37 100644 --- a/samples/ASPNET/Program.cs +++ b/samples/ASPNET/Program.cs @@ -3,6 +3,7 @@ // Add services to the container. builder.Services.AddControllers(); + // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); diff --git a/samples/ASPNET/WeatherForecasts/GetWeatherForecasts.cs b/samples/ASPNET/WeatherForecasts/GetWeatherForecasts.cs index 3edfa89..2cb61ed 100644 --- a/samples/ASPNET/WeatherForecasts/GetWeatherForecasts.cs +++ b/samples/ASPNET/WeatherForecasts/GetWeatherForecasts.cs @@ -8,18 +8,35 @@ public sealed record GetWeatherForecastsHandler : IQueryHandler> Handle(GetWeatherForecasts query, CancellationToken cancellationToken) + public ValueTask> Handle( + GetWeatherForecasts query, + CancellationToken cancellationToken + ) { - var result = Enumerable.Range(1, 5).Select(index => new WeatherForecast - { - Date = DateTime.Now.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] - }) - .ToArray(); + var result = Enumerable + .Range(1, 5) + .Select( + index => + new WeatherForecast + { + Date = DateTime.Now.AddDays(index), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + } + ) + .ToArray(); return new ValueTask>(result); } diff --git a/samples/ASPNET/WeatherForecasts/WeatherForecast.cs b/samples/ASPNET/WeatherForecasts/WeatherForecast.cs index a153aa0..4448b82 100644 --- a/samples/ASPNET/WeatherForecasts/WeatherForecast.cs +++ b/samples/ASPNET/WeatherForecasts/WeatherForecast.cs @@ -10,4 +10,4 @@ public class WeatherForecast public string? Summary { get; set; } } -} \ No newline at end of file +} diff --git a/samples/ASPNET_CleanArchitecture/AspNetSample.Api/Program.cs b/samples/ASPNET_CleanArchitecture/AspNetSample.Api/Program.cs index 740c214..6ccdb57 100644 --- a/samples/ASPNET_CleanArchitecture/AspNetSample.Api/Program.cs +++ b/samples/ASPNET_CleanArchitecture/AspNetSample.Api/Program.cs @@ -9,13 +9,19 @@ public static void Main(string[] args) public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .ConfigureLogging(builder => - builder.AddSimpleConsole(Options => + .ConfigureWebHostDefaults( + webBuilder => { - Options.SingleLine = true; - })); + webBuilder.UseStartup(); + } + ) + .ConfigureLogging( + builder => + builder.AddSimpleConsole( + Options => + { + Options.SingleLine = true; + } + ) + ); } diff --git a/samples/ASPNET_CleanArchitecture/AspNetSample.Api/Startup.cs b/samples/ASPNET_CleanArchitecture/AspNetSample.Api/Startup.cs index c0f9d77..0b17dcb 100644 --- a/samples/ASPNET_CleanArchitecture/AspNetSample.Api/Startup.cs +++ b/samples/ASPNET_CleanArchitecture/AspNetSample.Api/Startup.cs @@ -23,10 +23,12 @@ public void ConfigureServices(IServiceCollection services) services.AddApplication(); services.AddInfrastructure(); - services.AddSwaggerGen(c => - { - c.SwaggerDoc("v1", new OpenApiInfo { Title = "AspNetSample.Api", Version = "v1" }); - }); + services.AddSwaggerGen( + c => + { + c.SwaggerDoc("v1", new OpenApiInfo { Title = "AspNetSample.Api", Version = "v1" }); + } + ); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -43,9 +45,11 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) app.UseAuthorization(); - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); + app.UseEndpoints( + endpoints => + { + endpoints.MapControllers(); + } + ); } } diff --git a/samples/ASPNET_CleanArchitecture/AspNetSample.Application/Pipeline/ErrorLoggingBehaviour.cs b/samples/ASPNET_CleanArchitecture/AspNetSample.Application/Pipeline/ErrorLoggingBehaviour.cs index 0d1578b..515029a 100644 --- a/samples/ASPNET_CleanArchitecture/AspNetSample.Application/Pipeline/ErrorLoggingBehaviour.cs +++ b/samples/ASPNET_CleanArchitecture/AspNetSample.Application/Pipeline/ErrorLoggingBehaviour.cs @@ -4,7 +4,7 @@ namespace AspNetSample.Application; public sealed class ErrorLoggingBehaviour : IPipelineBehavior - where TMessage : IMessage + where TMessage : IMessage { private readonly ILogger> _logger; @@ -13,7 +13,11 @@ public ErrorLoggingBehaviour(ILogger> _logger = logger; } - public async ValueTask Handle(TMessage message, CancellationToken cancellationToken, MessageHandlerDelegate next) + public async ValueTask Handle( + TMessage message, + CancellationToken cancellationToken, + MessageHandlerDelegate next + ) { try { diff --git a/samples/ASPNET_CleanArchitecture/AspNetSample.Application/Pipeline/MessageValidatorBehaviour.cs b/samples/ASPNET_CleanArchitecture/AspNetSample.Application/Pipeline/MessageValidatorBehaviour.cs index e44682b..f36290d 100644 --- a/samples/ASPNET_CleanArchitecture/AspNetSample.Application/Pipeline/MessageValidatorBehaviour.cs +++ b/samples/ASPNET_CleanArchitecture/AspNetSample.Application/Pipeline/MessageValidatorBehaviour.cs @@ -3,9 +3,13 @@ namespace AspNetSample.Application; public sealed class MessageValidatorBehaviour : IPipelineBehavior - where TMessage : IValidate + where TMessage : IValidate { - public ValueTask Handle(TMessage message, CancellationToken cancellationToken, MessageHandlerDelegate next) + public ValueTask Handle( + TMessage message, + CancellationToken cancellationToken, + MessageHandlerDelegate next + ) { if (!message.IsValid(out var validationError)) throw new ValidationException(validationError); diff --git a/samples/ASPNET_CleanArchitecture/AspNetSample.Application/Todos/TodoItemQueryHandler.cs b/samples/ASPNET_CleanArchitecture/AspNetSample.Application/Todos/TodoItemQueryHandler.cs index 07804df..6012d22 100644 --- a/samples/ASPNET_CleanArchitecture/AspNetSample.Application/Todos/TodoItemQueryHandler.cs +++ b/samples/ASPNET_CleanArchitecture/AspNetSample.Application/Todos/TodoItemQueryHandler.cs @@ -15,8 +15,6 @@ public async ValueTask> Handle(GetTodoItems query, Canc { var items = await _repository.GetItems(cancellationToken); - return items - .Select(i => new TodoItemDto(i.Title, i.Text, i.Done)) - .ToArray(); + return items.Select(i => new TodoItemDto(i.Title, i.Text, i.Done)).ToArray(); } } diff --git a/samples/ASPNET_CleanArchitecture/AspNetSample.Application/ValidationException.cs b/samples/ASPNET_CleanArchitecture/AspNetSample.Application/ValidationException.cs index 6417429..c5c55c4 100644 --- a/samples/ASPNET_CleanArchitecture/AspNetSample.Application/ValidationException.cs +++ b/samples/ASPNET_CleanArchitecture/AspNetSample.Application/ValidationException.cs @@ -2,7 +2,8 @@ namespace AspNetSample.Application; public sealed class ValidationException : Exception { - public ValidationException(ValidationError validationError) : base("Validation error") => ValidationError = validationError; + public ValidationException(ValidationError validationError) : base("Validation error") => + ValidationError = validationError; public ValidationError ValidationError { get; } } diff --git a/samples/SimpleConsole/Program.cs b/samples/SimpleConsole/Program.cs index 9043d66..494ae0d 100644 --- a/samples/SimpleConsole/Program.cs +++ b/samples/SimpleConsole/Program.cs @@ -8,16 +8,18 @@ // This extensions method is generated, and is put in the "Microsoft.Extensions.DependencyInjection" namespace. // We override the namespace in the "MediatorOptions" attribute above. -services.AddMediator(options => -{ - options.Namespace = null; - options.ServiceLifetime = ServiceLifetime.Transient; -}); +services.AddMediator( + options => + { + options.Namespace = null; + options.ServiceLifetime = ServiceLifetime.Transient; + } +); // Standard handlers are added by default, but we need to add pipeline steps manually. // Here are two examples. services.AddSingleton(typeof(IPipelineBehavior<,>), typeof(GenericLoggerHandler<,>)); // This will run 1st -services.AddSingleton, PingValidator>(); // This will run 2nd +services.AddSingleton, PingValidator>(); // This will run 2nd var serviceProvider = services.BuildServiceProvider(); @@ -46,7 +48,11 @@ public sealed record Pong(Guid Id); public sealed class GenericLoggerHandler : IPipelineBehavior where TMessage : IMessage { - public async ValueTask Handle(TMessage message, CancellationToken cancellationToken, MessageHandlerDelegate next) + public async ValueTask Handle( + TMessage message, + CancellationToken cancellationToken, + MessageHandlerDelegate next + ) { Console.WriteLine("1) Running logger handler"); try @@ -65,7 +71,11 @@ public async ValueTask Handle(TMessage message, CancellationToken can public sealed class PingValidator : IPipelineBehavior { - public ValueTask Handle(Ping request, CancellationToken cancellationToken, MessageHandlerDelegate next) + public ValueTask Handle( + Ping request, + CancellationToken cancellationToken, + MessageHandlerDelegate next + ) { Console.WriteLine("2) Running ping validator"); if (request is null || request.Id == default) diff --git a/samples/SimpleConsoleAOT/Program.cs b/samples/SimpleConsoleAOT/Program.cs index 4fb07d9..36252c9 100644 --- a/samples/SimpleConsoleAOT/Program.cs +++ b/samples/SimpleConsoleAOT/Program.cs @@ -12,7 +12,7 @@ // Standard handlers are added by default, but we need to add pipeline steps manually. // Here are two examples. services.AddSingleton(typeof(IPipelineBehavior<,>), typeof(GenericLoggerHandler<,>)); // This will run 1st -services.AddSingleton, PingValidator>(); // This will run 2nd +services.AddSingleton, PingValidator>(); // This will run 2nd var serviceProvider = services.BuildServiceProvider(); @@ -41,7 +41,11 @@ public sealed record Pong(Guid Id); public sealed class GenericLoggerHandler : IPipelineBehavior where TMessage : IMessage { - public async ValueTask Handle(TMessage message, CancellationToken cancellationToken, MessageHandlerDelegate next) + public async ValueTask Handle( + TMessage message, + CancellationToken cancellationToken, + MessageHandlerDelegate next + ) { Console.WriteLine("1) Running logger handler"); try @@ -60,7 +64,11 @@ public async ValueTask Handle(TMessage message, CancellationToken can public sealed class PingValidator : IPipelineBehavior { - public ValueTask Handle(Ping request, CancellationToken cancellationToken, MessageHandlerDelegate next) + public ValueTask Handle( + Ping request, + CancellationToken cancellationToken, + MessageHandlerDelegate next + ) { Console.WriteLine("2) Running ping validator"); if (request is null || request.Id == default) diff --git a/samples/SimpleEndToEnd/Program.cs b/samples/SimpleEndToEnd/Program.cs index ecdc750..8ca0605 100644 --- a/samples/SimpleEndToEnd/Program.cs +++ b/samples/SimpleEndToEnd/Program.cs @@ -8,6 +8,7 @@ var services = new ServiceCollection(); services.AddMediator(); + // Ordering of pipeline behavior registrations matter! services.AddSingleton(typeof(IPipelineBehavior<,>), typeof(ErrorLoggerHandler<,>)); services.AddSingleton, PingValidator>(); @@ -32,13 +33,13 @@ var statsHandler = sp.GetRequiredService(); var (messageCount, messageErrorCount) = statsHandler.Stats; + // First Ping succeeded, second failed validation -Debug.Assert(messageCount == 2, "We sent 2 pings"); +Debug.Assert(messageCount == 2, "We sent 2 pings"); Debug.Assert(messageErrorCount == 1, "1 of them failed validation"); Console.WriteLine("Done!"); - // Types used below public sealed record Ping(Guid Id) : IRequest; @@ -55,7 +56,11 @@ public ValueTask Handle(Ping request, CancellationToken cancellationToken) public sealed class PingValidator : IPipelineBehavior { - public ValueTask Handle(Ping request, CancellationToken cancellationToken, MessageHandlerDelegate next) + public ValueTask Handle( + Ping request, + CancellationToken cancellationToken, + MessageHandlerDelegate next + ) { if (request is null || request.Id == default) throw new ArgumentException("Invalid input"); @@ -78,7 +83,11 @@ public ErrorLoggerHandler(IMediator mediator) _mediator = mediator; } - public async ValueTask Handle(TMessage message, CancellationToken cancellationToken, MessageHandlerDelegate next) + public async ValueTask Handle( + TMessage message, + CancellationToken cancellationToken, + MessageHandlerDelegate next + ) { try { diff --git a/samples/SimpleStreaming/Program.cs b/samples/SimpleStreaming/Program.cs index d6b1966..7ef1e03 100644 --- a/samples/SimpleStreaming/Program.cs +++ b/samples/SimpleStreaming/Program.cs @@ -38,7 +38,10 @@ public sealed record Pong(Guid Id); public sealed class PingHandler : IStreamRequestHandler { - public async IAsyncEnumerable Handle(StreamPing request, [EnumeratorCancellation] CancellationToken cancellationToken) + public async IAsyncEnumerable Handle( + StreamPing request, + [EnumeratorCancellation] CancellationToken cancellationToken + ) { for (int i = 0; i < 5; i++) { diff --git a/samples/WPFApp/MainWindow.xaml.cs b/samples/WPFApp/MainWindow.xaml.cs index 821bbb4..78d8f5e 100644 --- a/samples/WPFApp/MainWindow.xaml.cs +++ b/samples/WPFApp/MainWindow.xaml.cs @@ -36,22 +36,30 @@ public MainWindow() lvDataBinding.ItemsSource = _items; - _ = Task.Run(async () => - { - var sp = App.ServiceProvider; + _ = Task.Run( + async () => + { + var sp = App.ServiceProvider; - var mediator = sp.GetRequiredService(); + var mediator = sp.GetRequiredService(); - for (int i = 0; i < 100; i++) - { - var ping = new Ping(); - var pong = await mediator.Send(ping); - - lvDataBinding.Dispatcher.Invoke(() => { _items.Enqueue((ping, pong)); }, DispatcherPriority.Render); - - await Task.Delay(2000); + for (int i = 0; i < 100; i++) + { + var ping = new Ping(); + var pong = await mediator.Send(ping); + + lvDataBinding.Dispatcher.Invoke( + () => + { + _items.Enqueue((ping, pong)); + }, + DispatcherPriority.Render + ); + + await Task.Delay(2000); + } } - }); + ); } } diff --git a/samples/WPFApp/Properties/AssemblyInfo.cs b/samples/WPFApp/Properties/AssemblyInfo.cs index fe8d238..0fc0498 100644 --- a/samples/WPFApp/Properties/AssemblyInfo.cs +++ b/samples/WPFApp/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -33,9 +33,9 @@ [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located - //(used if a resource is not found in the page, - // or application resource dictionaries) + //(used if a resource is not found in the page, + // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located - //(used if a resource is not found in the page, - // app, or any theme specific resource dictionaries) +//(used if a resource is not found in the page, +// app, or any theme specific resource dictionaries) )] diff --git a/src/Mediator.SourceGenerator.Implementation/Analysis/CompilationAnalyzer.cs b/src/Mediator.SourceGenerator.Implementation/Analysis/CompilationAnalyzer.cs index 2c98dfe..c51b1a9 100644 --- a/src/Mediator.SourceGenerator.Implementation/Analysis/CompilationAnalyzer.cs +++ b/src/Mediator.SourceGenerator.Implementation/Analysis/CompilationAnalyzer.cs @@ -32,14 +32,11 @@ internal sealed class CompilationAnalyzer private readonly INamedTypeSymbol _notificationHandlerInterfaceSymbol; private readonly INamedTypeSymbol _notificationInterfaceSymbol; - public IEnumerable RequestMessages => - _requestMessages.Where(r => r.Handler is not null); + public IEnumerable RequestMessages => _requestMessages.Where(r => r.Handler is not null); - public IEnumerable NotificationMessages => - _notificationMessages; + public IEnumerable NotificationMessages => _notificationMessages; - public IEnumerable RequestMessageHandlers => - _requestMessageHandlers; + public IEnumerable RequestMessageHandlers => _requestMessageHandlers; public IEnumerable NotificationMessageHandlers => _notificationMessageHandlers.Where(h => !h.IsOpenGeneric); @@ -51,9 +48,11 @@ internal sealed class CompilationAnalyzer public bool HasCommands => _requestMessages.Any(r => r.Handler is not null && r.MessageType == "Command"); public bool HasQueries => _requestMessages.Any(r => r.Handler is not null && r.MessageType == "Query"); - public bool HasStreamRequests => _requestMessages.Any(r => r.Handler is not null && r.MessageType == "StreamRequest"); + public bool HasStreamRequests => + _requestMessages.Any(r => r.Handler is not null && r.MessageType == "StreamRequest"); public bool HasStreamQueries => _requestMessages.Any(r => r.Handler is not null && r.MessageType == "StreamQuery"); - public bool HasStreamCommands => _requestMessages.Any(r => r.Handler is not null && r.MessageType == "StreamCommand"); + public bool HasStreamCommands => + _requestMessages.Any(r => r.Handler is not null && r.MessageType == "StreamCommand"); public bool HasAnyRequest => HasRequests || HasCommands || HasQueries; @@ -61,16 +60,24 @@ internal sealed class CompilationAnalyzer public bool HasNotifications => _notificationMessages.Any(); - public IEnumerable IRequestMessages => _requestMessages.Where(r => r.Handler is not null && r.MessageType == "Request"); - public IEnumerable ICommandMessages => _requestMessages.Where(r => r.Handler is not null && r.MessageType == "Command"); - public IEnumerable IQueryMessages => _requestMessages.Where(r => r.Handler is not null && r.MessageType == "Query"); - - public IEnumerable IStreamRequestMessages => _requestMessages.Where(r => r.Handler is not null && r.MessageType == "StreamRequest"); - public IEnumerable IStreamQueryMessages => _requestMessages.Where(r => r.Handler is not null && r.MessageType == "StreamQuery"); - public IEnumerable IStreamCommandMessages => _requestMessages.Where(r => r.Handler is not null && r.MessageType == "StreamCommand"); - - public IEnumerable IMessages => _requestMessages.Where(r => r.Handler is not null && !r.IsStreaming); - public IEnumerable IStreamMessages => _requestMessages.Where(r => r.Handler is not null && r.IsStreaming); + public IEnumerable IRequestMessages => + _requestMessages.Where(r => r.Handler is not null && r.MessageType == "Request"); + public IEnumerable ICommandMessages => + _requestMessages.Where(r => r.Handler is not null && r.MessageType == "Command"); + public IEnumerable IQueryMessages => + _requestMessages.Where(r => r.Handler is not null && r.MessageType == "Query"); + + public IEnumerable IStreamRequestMessages => + _requestMessages.Where(r => r.Handler is not null && r.MessageType == "StreamRequest"); + public IEnumerable IStreamQueryMessages => + _requestMessages.Where(r => r.Handler is not null && r.MessageType == "StreamQuery"); + public IEnumerable IStreamCommandMessages => + _requestMessages.Where(r => r.Handler is not null && r.MessageType == "StreamCommand"); + + public IEnumerable IMessages => + _requestMessages.Where(r => r.Handler is not null && !r.IsStreaming); + public IEnumerable IStreamMessages => + _requestMessages.Where(r => r.Handler is not null && r.IsStreaming); private bool _hasErrors; @@ -99,8 +106,9 @@ internal sealed class CompilationAnalyzer public bool ServiceLifetimeIsTransient => ServiceLifetimeSymbol.Name == "Transient"; - public bool IsTestRun => (_context.Compilation.AssemblyName?.StartsWith("Mediator.Tests") ?? false) || - (_context.Compilation.AssemblyName?.StartsWith("Mediator.SmokeTest") ?? false); + public bool IsTestRun => + (_context.Compilation.AssemblyName?.StartsWith("Mediator.Tests") ?? false) + || (_context.Compilation.AssemblyName?.StartsWith("Mediator.SmokeTest") ?? false); public CompilationAnalyzer(in CompilationAnalyzerContext context) { @@ -139,7 +147,10 @@ private void TryLoadUnitSymbol(out INamedTypeSymbol UnitSymbol) if (unitSymbol is null) { UnitSymbol = null!; - ReportDiagnostic(unitSymbolName, ((in CompilationAnalyzerContext c, string name) => c.ReportRequiredSymbolNotFound(name))); + ReportDiagnostic( + unitSymbolName, + ((in CompilationAnalyzerContext c, string name) => c.ReportRequiredSymbolNotFound(name)) + ); } else { @@ -151,16 +162,20 @@ private void TryLoadBaseHandlerSymbols(out INamedTypeSymbol[] _baseHandlerSymbol { var baseHandlerSymbolNames = new[] { - $"{Constants.MediatorLib}.IRequestHandler`1", $"{Constants.MediatorLib}.IRequestHandler`2", - $"{Constants.MediatorLib}.IStreamRequestHandler`2", $"{Constants.MediatorLib}.ICommandHandler`1", - $"{Constants.MediatorLib}.ICommandHandler`2", $"{Constants.MediatorLib}.IStreamCommandHandler`2", - $"{Constants.MediatorLib}.IQueryHandler`2", $"{Constants.MediatorLib}.IStreamQueryHandler`2", + $"{Constants.MediatorLib}.IRequestHandler`1", + $"{Constants.MediatorLib}.IRequestHandler`2", + $"{Constants.MediatorLib}.IStreamRequestHandler`2", + $"{Constants.MediatorLib}.ICommandHandler`1", + $"{Constants.MediatorLib}.ICommandHandler`2", + $"{Constants.MediatorLib}.IStreamCommandHandler`2", + $"{Constants.MediatorLib}.IQueryHandler`2", + $"{Constants.MediatorLib}.IStreamQueryHandler`2", $"{Constants.MediatorLib}.INotificationHandler`1", }; - var baseHandlerSymbols = - baseHandlerSymbolNames.Select(n => (Name: n, Symbol: _context.Compilation.GetTypeByMetadataName(n)?.OriginalDefinition)) - .ToArray(); + var baseHandlerSymbols = baseHandlerSymbolNames + .Select(n => (Name: n, Symbol: _context.Compilation.GetTypeByMetadataName(n)?.OriginalDefinition)) + .ToArray(); _baseHandlerSymbols = Array.Empty(); if (baseHandlerSymbols.Any(s => s.Symbol is null)) @@ -169,18 +184,22 @@ private void TryLoadBaseHandlerSymbols(out INamedTypeSymbol[] _baseHandlerSymbol { if (symbol is not null) continue; - ReportDiagnostic(name, ((in CompilationAnalyzerContext c, string name) => c.ReportRequiredSymbolNotFound(name))); + ReportDiagnostic( + name, + ((in CompilationAnalyzerContext c, string name) => c.ReportRequiredSymbolNotFound(name)) + ); } } else { - _baseHandlerSymbols = baseHandlerSymbols - .Select(s => s.Symbol!) - .ToArray(); + _baseHandlerSymbols = baseHandlerSymbols.Select(s => s.Symbol!).ToArray(); } } - private void TryLoadDISymbols(out INamedTypeSymbol _serviceLifetimeEnumSymbol, out IFieldSymbol SingletonServiceLifetimeSymbol) + private void TryLoadDISymbols( + out INamedTypeSymbol _serviceLifetimeEnumSymbol, + out IFieldSymbol SingletonServiceLifetimeSymbol + ) { var serviceLifetimeEnumSymbolName = "Microsoft.Extensions.DependencyInjection.ServiceLifetime"; var serviceLifetimeEnumSymbol = _context.Compilation.GetTypeByMetadataName(serviceLifetimeEnumSymbolName); @@ -188,28 +207,40 @@ private void TryLoadDISymbols(out INamedTypeSymbol _serviceLifetimeEnumSymbol, o { _serviceLifetimeEnumSymbol = null!; SingletonServiceLifetimeSymbol = null!; - ReportDiagnostic(serviceLifetimeEnumSymbolName, ((in CompilationAnalyzerContext c, string name) => c.ReportRequiredSymbolNotFound(name))); + ReportDiagnostic( + serviceLifetimeEnumSymbolName, + ((in CompilationAnalyzerContext c, string name) => c.ReportRequiredSymbolNotFound(name)) + ); } else { _serviceLifetimeEnumSymbol = serviceLifetimeEnumSymbol; - SingletonServiceLifetimeSymbol = (IFieldSymbol)_serviceLifetimeEnumSymbol.GetMembers().Single(m => m.Name == "Singleton"); + SingletonServiceLifetimeSymbol = (IFieldSymbol)_serviceLifetimeEnumSymbol + .GetMembers() + .Single(m => m.Name == "Singleton"); } } - private void TryLoadBaseMessageSymbols(out INamedTypeSymbol[] _baseMessageSymbols, out INamedTypeSymbol _notificationInterfaceSymbol) + private void TryLoadBaseMessageSymbols( + out INamedTypeSymbol[] _baseMessageSymbols, + out INamedTypeSymbol _notificationInterfaceSymbol + ) { var baseMessageSymbolNames = new[] { - $"{Constants.MediatorLib}.IRequest", $"{Constants.MediatorLib}.IRequest`1", - $"{Constants.MediatorLib}.IStreamRequest`1", $"{Constants.MediatorLib}.ICommand", - $"{Constants.MediatorLib}.ICommand`1", $"{Constants.MediatorLib}.IStreamCommand`1", - $"{Constants.MediatorLib}.IQuery`1", $"{Constants.MediatorLib}.IStreamQuery`1", + $"{Constants.MediatorLib}.IRequest", + $"{Constants.MediatorLib}.IRequest`1", + $"{Constants.MediatorLib}.IStreamRequest`1", + $"{Constants.MediatorLib}.ICommand", + $"{Constants.MediatorLib}.ICommand`1", + $"{Constants.MediatorLib}.IStreamCommand`1", + $"{Constants.MediatorLib}.IQuery`1", + $"{Constants.MediatorLib}.IStreamQuery`1", $"{Constants.MediatorLib}.INotification", }; - var baseMessageSymbols = - baseMessageSymbolNames.Select(n => (Name: n, Symbol: _context.Compilation.GetTypeByMetadataName(n)?.OriginalDefinition)) - .ToArray(); + var baseMessageSymbols = baseMessageSymbolNames + .Select(n => (Name: n, Symbol: _context.Compilation.GetTypeByMetadataName(n)?.OriginalDefinition)) + .ToArray(); _baseMessageSymbols = Array.Empty(); if (baseMessageSymbols.Any(s => s.Symbol is null)) @@ -219,14 +250,15 @@ private void TryLoadBaseMessageSymbols(out INamedTypeSymbol[] _baseMessageSymbol { if (symbol is not null) continue; - ReportDiagnostic(name, ((in CompilationAnalyzerContext c, string name) => c.ReportRequiredSymbolNotFound(name))); + ReportDiagnostic( + name, + ((in CompilationAnalyzerContext c, string name) => c.ReportRequiredSymbolNotFound(name)) + ); } } else { - _baseMessageSymbols = baseMessageSymbols - .Select(s => s.Symbol!) - .ToArray(); + _baseMessageSymbols = baseMessageSymbols.Select(s => s.Symbol!).ToArray(); _notificationInterfaceSymbol = _baseMessageSymbols[_baseMessageSymbols.Length - 1]; } } @@ -284,12 +316,17 @@ private void PopulateMetadata(Queue queue) if (kvp.Value is not RequestMessage message) continue; - ReportDiagnostic(message.Symbol, (in CompilationAnalyzerContext c, INamedTypeSymbol s) => c.ReportMessageWithoutHandler(s)); + ReportDiagnostic( + message.Symbol, + (in CompilationAnalyzerContext c, INamedTypeSymbol s) => c.ReportMessageWithoutHandler(s) + ); } foreach (var notificationMessage in _notificationMessages) { - var handlerInterface = _baseHandlerSymbols[_baseHandlerSymbols.Length - 1].Construct(notificationMessage.Symbol); + var handlerInterface = _baseHandlerSymbols[_baseHandlerSymbols.Length - 1].Construct( + notificationMessage.Symbol + ); foreach (var notificationMessageHandler in _notificationMessageHandlers) { @@ -319,7 +356,11 @@ private void PopulateMetadata(Queue queue) const int IS_REQUEST = 3; const int IS_NOTIFICATION = 4; - void ProcessMember(Queue queue, INamespaceOrTypeSymbol member, Dictionary mapping) + void ProcessMember( + Queue queue, + INamespaceOrTypeSymbol member, + Dictionary mapping + ) { if (member is INamespaceSymbol childNsSymbol) { @@ -351,19 +392,30 @@ void ProcessMember(Queue queue, INamespaceOrTypeSymbol m } } - bool ProcessInterface(int i, INamedTypeSymbol typeSymbol, INamedTypeSymbol typeInterfaceSymbol, bool isStruct, Dictionary mapping) + bool ProcessInterface( + int i, + INamedTypeSymbol typeSymbol, + INamedTypeSymbol typeInterfaceSymbol, + bool isStruct, + Dictionary mapping + ) { var codeOfInterest = IsInteresting(typeInterfaceSymbol); switch (codeOfInterest) { - case NOT_RELEVANT: break; // Continue loop + case NOT_RELEVANT: + break; // Continue loop case IS_REQUEST_HANDLER: case IS_NOTIFICATION_HANDLER: + { if (isStruct) { // Handlers must be classes - ReportDiagnostic(typeSymbol, (in CompilationAnalyzerContext c, INamedTypeSymbol s) => c.ReportInvalidHandlerType(s)); + ReportDiagnostic( + typeSymbol, + (in CompilationAnalyzerContext c, INamedTypeSymbol s) => c.ReportInvalidHandlerType(s) + ); return false; } @@ -378,11 +430,18 @@ bool ProcessInterface(int i, INamedTypeSymbol typeSymbol, INamedTypeSymbol typeI if (IsOpenGeneric(typeSymbol)) { // Handlers must be classes - ReportDiagnostic(typeSymbol, (in CompilationAnalyzerContext c, INamedTypeSymbol s) => c.ReportOpenGenericRequestHandler(s)); + ReportDiagnostic( + typeSymbol, + (in CompilationAnalyzerContext c, INamedTypeSymbol s) => + c.ReportOpenGenericRequestHandler(s) + ); return false; } - var messageType = typeInterfaceSymbol.Name.Substring(1, typeInterfaceSymbol.Name.IndexOf("Handler") - 1); + var messageType = typeInterfaceSymbol.Name.Substring( + 1, + typeInterfaceSymbol.Name.IndexOf("Handler") - 1 + ); var handler = new RequestMessageHandler(typeSymbol, messageType, this); var requestMessageSymbol = (INamedTypeSymbol)typeInterfaceSymbol.TypeArguments[0]; @@ -391,7 +450,11 @@ bool ProcessInterface(int i, INamedTypeSymbol typeSymbol, INamedTypeSymbol typeI if (requestMessageObj is not RequestMessage requestMessage) { // Signal that we have duplicates - ReportDiagnostic(typeSymbol, (in CompilationAnalyzerContext c, INamedTypeSymbol s) => c.ReportMultipleHandlers(s)); + ReportDiagnostic( + typeSymbol, + (in CompilationAnalyzerContext c, INamedTypeSymbol s) => + c.ReportMultipleHandlers(s) + ); return false; } mapping[requestMessageSymbol] = null; @@ -411,24 +474,31 @@ bool ProcessInterface(int i, INamedTypeSymbol typeSymbol, INamedTypeSymbol typeI } break; case IS_REQUEST: + { - var responseMessageSymbol = typeInterfaceSymbol.TypeArguments.Length > 0 ? - (INamedTypeSymbol)typeInterfaceSymbol.TypeArguments[0] : - UnitSymbol; + var responseMessageSymbol = + typeInterfaceSymbol.TypeArguments.Length > 0 + ? (INamedTypeSymbol)typeInterfaceSymbol.TypeArguments[0] + : UnitSymbol; if (IsAlreadyHandledByDerivedInterface(i, 0, typeSymbol, typeInterfaceSymbol)) break; - var messageType = typeInterfaceSymbol.Name.IndexOf('<') == -1 ? - typeInterfaceSymbol.Name.Substring(1) : - typeInterfaceSymbol.Name.Substring(1, typeInterfaceSymbol.Name.IndexOf('<') - 1); + var messageType = + typeInterfaceSymbol.Name.IndexOf('<') == -1 + ? typeInterfaceSymbol.Name.Substring(1) + : typeInterfaceSymbol.Name.Substring(1, typeInterfaceSymbol.Name.IndexOf('<') - 1); var message = new RequestMessage(typeSymbol, responseMessageSymbol, messageType, this); if (!_requestMessages.Add(message)) { // If this symbol has already been added, // the type implements multiple base message types. - ReportDiagnostic(typeSymbol, (in CompilationAnalyzerContext c, INamedTypeSymbol s) => c.ReportMessageDerivesFromMultipleMessageInterfaces(s)); + ReportDiagnostic( + typeSymbol, + (in CompilationAnalyzerContext c, INamedTypeSymbol s) => + c.ReportMessageDerivesFromMultipleMessageInterfaces(s) + ); return false; } else @@ -446,12 +516,17 @@ bool ProcessInterface(int i, INamedTypeSymbol typeSymbol, INamedTypeSymbol typeI } break; case IS_NOTIFICATION: + { if (!_notificationMessages.Add(new NotificationMessage(typeSymbol, this))) { // If this symbol has already been added, // the type implements multiple base message types. - ReportDiagnostic(typeSymbol, (in CompilationAnalyzerContext c, INamedTypeSymbol s) => c.ReportMessageDerivesFromMultipleMessageInterfaces(s)); + ReportDiagnostic( + typeSymbol, + (in CompilationAnalyzerContext c, INamedTypeSymbol s) => + c.ReportMessageDerivesFromMultipleMessageInterfaces(s) + ); return false; } } @@ -469,18 +544,18 @@ int IsInteresting(INamedTypeSymbol interfaceSymbol) { var baseSymbol = _baseHandlerSymbols[i]; if (_symbolComparer.Equals(baseSymbol, originalInterfaceSymbol)) - return _symbolComparer.Equals(baseSymbol, _notificationHandlerInterfaceSymbol) ? - IS_NOTIFICATION_HANDLER : - IS_REQUEST_HANDLER; + return _symbolComparer.Equals(baseSymbol, _notificationHandlerInterfaceSymbol) + ? IS_NOTIFICATION_HANDLER + : IS_REQUEST_HANDLER; } for (int i = 0; i < _baseMessageSymbols.Length; i++) { var baseSymbol = _baseMessageSymbols[i]; if (_symbolComparer.Equals(baseSymbol, originalInterfaceSymbol)) - return _symbolComparer.Equals(baseSymbol, _notificationInterfaceSymbol) ? - IS_NOTIFICATION : - IS_REQUEST; + return _symbolComparer.Equals(baseSymbol, _notificationInterfaceSymbol) + ? IS_NOTIFICATION + : IS_REQUEST; } return NOT_RELEVANT; @@ -493,9 +568,10 @@ bool IsAlreadyHandledByDerivedInterface( INamedTypeSymbol typeInterfaceSymbol ) { - var mightSkip = typeInterfaceSymbol.TypeArguments.Length > responseTypeArgumentIndex && - typeInterfaceSymbol.TypeArguments[responseTypeArgumentIndex] is INamedTypeSymbol responseTypeSymbol && - _symbolComparer.Equals(responseTypeSymbol, UnitSymbol); + var mightSkip = + typeInterfaceSymbol.TypeArguments.Length > responseTypeArgumentIndex + && typeInterfaceSymbol.TypeArguments[responseTypeArgumentIndex] is INamedTypeSymbol responseTypeSymbol + && _symbolComparer.Equals(responseTypeSymbol, UnitSymbol); if (!mightSkip) return false; @@ -532,13 +608,16 @@ private void TryParseConfiguration(CancellationToken cancellationToken) } var attrs = compilation.Assembly.GetAttributes(); - var optionsAttr = attrs.SingleOrDefault(a => - { - if (a.AttributeClass is null) - return false; - var attributeFullName = a.AttributeClass.GetTypeSymbolFullName(withGlobalPrefix: false); - return attributeFullName == "Mediator.MediatorOptionsAttribute" || attributeFullName == "MediatorOptions"; - }); + var optionsAttr = attrs.SingleOrDefault( + a => + { + if (a.AttributeClass is null) + return false; + var attributeFullName = a.AttributeClass.GetTypeSymbolFullName(withGlobalPrefix: false); + return attributeFullName == "Mediator.MediatorOptionsAttribute" + || attributeFullName == "MediatorOptions"; + } + ); if (optionsAttr is not null) ProcessAttributeConfiguration(optionsAttr, configuredByAddMediator, cancellationToken); } @@ -598,7 +677,11 @@ CancellationToken cancellationToken } } - private void ProcessAttributeConfiguration(AttributeData optionsAttr, bool configuredByAddMediator, CancellationToken cancellationToken) + private void ProcessAttributeConfiguration( + AttributeData optionsAttr, + bool configuredByAddMediator, + CancellationToken cancellationToken + ) { var compilation = _context.Compilation; @@ -625,19 +708,30 @@ private void ProcessAttributeConfiguration(AttributeData optionsAttr, bool confi var attrFieldName = attrArg.NameEquals.Name.ToString(); if (attrFieldName == "ServiceLifetime") { - var identifierNameSyntax = (IdentifierNameSyntax)((MemberAccessExpressionSyntax)attrArg.Expression).Name; - _configuredLifetimeSymbol = GetServiceLifetimeSymbol(identifierNameSyntax, semanticModel, cancellationToken); + var identifierNameSyntax = (IdentifierNameSyntax)( + (MemberAccessExpressionSyntax)attrArg.Expression + ).Name; + _configuredLifetimeSymbol = GetServiceLifetimeSymbol( + identifierNameSyntax, + semanticModel, + cancellationToken + ); } else if (attrFieldName == "Namespace") { - var namespaceArg = semanticModel.GetConstantValue(attrArg.Expression, cancellationToken).Value as string; + var namespaceArg = + semanticModel.GetConstantValue(attrArg.Expression, cancellationToken).Value as string; if (!string.IsNullOrWhiteSpace(namespaceArg)) MediatorNamespace = namespaceArg!; } } } - private bool ProcessAddMediatorAssignmentStatement(AssignmentExpressionSyntax assignment, SemanticModel semanticModel, CancellationToken cancellationToken) + private bool ProcessAddMediatorAssignmentStatement( + AssignmentExpressionSyntax assignment, + SemanticModel semanticModel, + CancellationToken cancellationToken + ) { var opt = ((MemberAccessExpressionSyntax)assignment.Left).Name.Identifier.Text; if (opt == "Namespace") @@ -671,7 +765,11 @@ private bool ProcessAddMediatorAssignmentStatement(AssignmentExpressionSyntax as if (assignment.Right is MemberAccessExpressionSyntax enumAccess) { var identifierNameSyntax = (IdentifierNameSyntax)enumAccess.Name; - _configuredLifetimeSymbol = GetServiceLifetimeSymbol(identifierNameSyntax, semanticModel, cancellationToken); + _configuredLifetimeSymbol = GetServiceLifetimeSymbol( + identifierNameSyntax, + semanticModel, + cancellationToken + ); } else if (assignment.Right is IdentifierNameSyntax identifier) { @@ -691,8 +789,11 @@ private bool ProcessAddMediatorAssignmentStatement(AssignmentExpressionSyntax as return true; - - string? TryResolveNamespaceIdentifier(IdentifierNameSyntax identifier, SemanticModel semanticModel, CancellationToken cancellationToken) + string? TryResolveNamespaceIdentifier( + IdentifierNameSyntax identifier, + SemanticModel semanticModel, + CancellationToken cancellationToken + ) { var variableSymbol = semanticModel.GetSymbolInfo(identifier, cancellationToken).Symbol; if (variableSymbol is null) @@ -708,7 +809,11 @@ private bool ProcessAddMediatorAssignmentStatement(AssignmentExpressionSyntax as return null; } - string? TryResolveNamespaceSymbol(ISymbol symbol, SemanticModel semanticModel, CancellationToken cancellationToken) + string? TryResolveNamespaceSymbol( + ISymbol symbol, + SemanticModel semanticModel, + CancellationToken cancellationToken + ) { if (symbol is IFieldSymbol fieldSymbol && fieldSymbol.HasConstantValue) return fieldSymbol.ConstantValue as string; @@ -718,11 +823,11 @@ private bool ProcessAddMediatorAssignmentStatement(AssignmentExpressionSyntax as var syntaxReferences = symbol.DeclaringSyntaxReferences; var syntaxNode = syntaxReferences.First().GetSyntax(cancellationToken); - var initializerExpression = syntaxNode is VariableDeclaratorSyntax variableDeclarator ? - variableDeclarator.Initializer?.Value : - syntaxNode is PropertyDeclarationSyntax propertyDeclaration ? - propertyDeclaration.Initializer?.Value : - null; + var initializerExpression = syntaxNode is VariableDeclaratorSyntax variableDeclarator + ? variableDeclarator.Initializer?.Value + : syntaxNode is PropertyDeclarationSyntax propertyDeclaration + ? propertyDeclaration.Initializer?.Value + : null; if (initializerExpression is null) { @@ -740,10 +845,17 @@ syntaxNode is PropertyDeclarationSyntax propertyDeclaration ? } } - private IFieldSymbol? GetServiceLifetimeSymbol(IdentifierNameSyntax identifierNameSyntax, SemanticModel semanticModel, CancellationToken cancellationToken) + private IFieldSymbol? GetServiceLifetimeSymbol( + IdentifierNameSyntax identifierNameSyntax, + SemanticModel semanticModel, + CancellationToken cancellationToken + ) { var symbol = semanticModel.GetSymbolInfo(identifierNameSyntax, cancellationToken).Symbol; - if (symbol is IFieldSymbol lifetimeSymbol && SymbolEqualityComparer.Default.Equals(_serviceLifetimeEnumSymbol, lifetimeSymbol.ContainingType)) + if ( + symbol is IFieldSymbol lifetimeSymbol + && SymbolEqualityComparer.Default.Equals(_serviceLifetimeEnumSymbol, lifetimeSymbol.ContainingType) + ) return lifetimeSymbol; if (symbol is IFieldSymbol fieldSymbol) @@ -756,27 +868,37 @@ syntaxNode is PropertyDeclarationSyntax propertyDeclaration ? return null; } - private IFieldSymbol? TryGetServiceLifetimeSymbol(ISymbol symbol, SemanticModel semanticModel, CancellationToken cancellationToken) + private IFieldSymbol? TryGetServiceLifetimeSymbol( + ISymbol symbol, + SemanticModel semanticModel, + CancellationToken cancellationToken + ) { if (symbol is IFieldSymbol fieldSymbol && fieldSymbol.HasConstantValue) { var value = (int)fieldSymbol.ConstantValue!; - return _serviceLifetimeEnumSymbol.GetMembers().OfType().Single(m => (int)m.ConstantValue! == value); + return _serviceLifetimeEnumSymbol + .GetMembers() + .OfType() + .Single(m => (int)m.ConstantValue! == value); } if (symbol is ILocalSymbol localSymbol && localSymbol.HasConstantValue) { var value = (int)localSymbol.ConstantValue!; - return _serviceLifetimeEnumSymbol.GetMembers().OfType().Single(m => (int)m.ConstantValue! == value); + return _serviceLifetimeEnumSymbol + .GetMembers() + .OfType() + .Single(m => (int)m.ConstantValue! == value); } var syntaxReferences = symbol.DeclaringSyntaxReferences; var syntaxNode = syntaxReferences.First().GetSyntax(cancellationToken); - var initializerExpression = syntaxNode is VariableDeclaratorSyntax variableDeclarator ? - variableDeclarator.Initializer?.Value : - syntaxNode is PropertyDeclarationSyntax propertyDeclaration ? - propertyDeclaration.Initializer?.Value : - null; + var initializerExpression = syntaxNode is VariableDeclaratorSyntax variableDeclarator + ? variableDeclarator.Initializer?.Value + : syntaxNode is PropertyDeclarationSyntax propertyDeclaration + ? propertyDeclaration.Initializer?.Value + : null; if (initializerExpression is null) { @@ -787,7 +909,10 @@ syntaxNode is PropertyDeclarationSyntax propertyDeclaration ? if (initializerExpression is LiteralExpressionSyntax literal) { var value = (int)literal.Token.Value!; - return _serviceLifetimeEnumSymbol.GetMembers().OfType().Single(m => (int)m.ConstantValue! == value); + return _serviceLifetimeEnumSymbol + .GetMembers() + .OfType() + .Single(m => (int)m.ConstantValue! == value); } if (initializerExpression is MemberAccessExpressionSyntax memberAccess) @@ -800,6 +925,7 @@ syntaxNode is PropertyDeclarationSyntax propertyDeclaration ? } private delegate Diagnostic ReportDiagnosticDelegate(in CompilationAnalyzerContext context, T state); + private void ReportDiagnostic(T state, ReportDiagnosticDelegate del) { var diagnostic = del(in _context, state); @@ -807,6 +933,7 @@ private void ReportDiagnostic(T state, ReportDiagnosticDelegate del) } private delegate Diagnostic ReportDiagnosticDelegate(in CompilationAnalyzerContext context); + private void ReportDiagnostic(ReportDiagnosticDelegate del) { var diagnostic = del(in _context); diff --git a/src/Mediator.SourceGenerator.Implementation/Analysis/InvocationSyntaxReceiver.cs b/src/Mediator.SourceGenerator.Implementation/Analysis/InvocationSyntaxReceiver.cs index 4a09cd0..1185707 100644 --- a/src/Mediator.SourceGenerator.Implementation/Analysis/InvocationSyntaxReceiver.cs +++ b/src/Mediator.SourceGenerator.Implementation/Analysis/InvocationSyntaxReceiver.cs @@ -13,7 +13,10 @@ public void OnVisitSyntaxNode(SyntaxNode context) public static bool ShouldVisit(SyntaxNode context, out InvocationExpressionSyntax? invocation) { invocation = null; - if (context is not InvocationExpressionSyntax { Expression: MemberAccessExpressionSyntax identifier } invocationSyntax) + if ( + context + is not InvocationExpressionSyntax { Expression: MemberAccessExpressionSyntax identifier } invocationSyntax + ) return false; if (identifier.Name.Identifier.ValueText != "AddMediator") return false; diff --git a/src/Mediator.SourceGenerator.Implementation/Analysis/MessageHandler.cs b/src/Mediator.SourceGenerator.Implementation/Analysis/MessageHandler.cs index ce6c761..daa33d4 100644 --- a/src/Mediator.SourceGenerator.Implementation/Analysis/MessageHandler.cs +++ b/src/Mediator.SourceGenerator.Implementation/Analysis/MessageHandler.cs @@ -4,10 +4,7 @@ namespace Mediator.SourceGenerator; internal abstract class MessageHandler : SymbolMetadata> { - protected MessageHandler(INamedTypeSymbol symbol, CompilationAnalyzer analyzer) - : base(symbol, analyzer) - { - } + protected MessageHandler(INamedTypeSymbol symbol, CompilationAnalyzer analyzer) : base(symbol, analyzer) { } public bool IsOpenGeneric => Symbol.TypeArguments.Length > 0; diff --git a/src/Mediator.SourceGenerator.Implementation/Analysis/NotificationMessage.cs b/src/Mediator.SourceGenerator.Implementation/Analysis/NotificationMessage.cs index 7c72cb4..cb79b8c 100644 --- a/src/Mediator.SourceGenerator.Implementation/Analysis/NotificationMessage.cs +++ b/src/Mediator.SourceGenerator.Implementation/Analysis/NotificationMessage.cs @@ -6,8 +6,7 @@ internal sealed class NotificationMessage : SymbolMetadata { private readonly HashSet _handlers; - public NotificationMessage(INamedTypeSymbol symbol, CompilationAnalyzer analyzer) - : base(symbol, analyzer) + public NotificationMessage(INamedTypeSymbol symbol, CompilationAnalyzer analyzer) : base(symbol, analyzer) { _handlers = new(); } @@ -16,13 +15,18 @@ public NotificationMessage(INamedTypeSymbol symbol, CompilationAnalyzer analyzer public string FullName => Symbol.GetTypeSymbolFullName(); - public string IdentifierFullName => Symbol.GetTypeSymbolFullName(withGlobalPrefix: false, includeTypeParameters: false).Replace("global::", "").Replace('.', '_'); + public string IdentifierFullName => + Symbol + .GetTypeSymbolFullName(withGlobalPrefix: false, includeTypeParameters: false) + .Replace("global::", "") + .Replace('.', '_'); public int HandlerCount => _handlers.Count; public string ServiceLifetime => Analyzer.ServiceLifetime; - public string HandlerTypeOfExpression => $"typeof(global::Mediator.INotificationHandler<{Symbol.GetTypeSymbolFullName()}>)"; + public string HandlerTypeOfExpression => + $"typeof(global::Mediator.INotificationHandler<{Symbol.GetTypeSymbolFullName()}>)"; public IEnumerable HandlerServicesRegistrationBlock { diff --git a/src/Mediator.SourceGenerator.Implementation/Analysis/NotificationMessageHandler.cs b/src/Mediator.SourceGenerator.Implementation/Analysis/NotificationMessageHandler.cs index e54a6a3..6162717 100644 --- a/src/Mediator.SourceGenerator.Implementation/Analysis/NotificationMessageHandler.cs +++ b/src/Mediator.SourceGenerator.Implementation/Analysis/NotificationMessageHandler.cs @@ -2,13 +2,10 @@ namespace Mediator.SourceGenerator; internal sealed class NotificationMessageHandler : MessageHandler { - public NotificationMessageHandler(INamedTypeSymbol symbol, CompilationAnalyzer analyzer) - : base(symbol, analyzer) - { - } + public NotificationMessageHandler(INamedTypeSymbol symbol, CompilationAnalyzer analyzer) : base(symbol, analyzer) + { } - public string OpenGenericTypeOfExpression => - $"typeof(global::Mediator.INotificationHandler<>)"; + public string OpenGenericTypeOfExpression => $"typeof(global::Mediator.INotificationHandler<>)"; public string OpenGenericServiceRegistrationBlock => $"services.Add(new SD({OpenGenericTypeOfExpression}, {TypeOfExpression(false)}, {ServiceLifetime}));"; diff --git a/src/Mediator.SourceGenerator.Implementation/Analysis/RequestMessage.cs b/src/Mediator.SourceGenerator.Implementation/Analysis/RequestMessage.cs index edc5390..d0378fa 100644 --- a/src/Mediator.SourceGenerator.Implementation/Analysis/RequestMessage.cs +++ b/src/Mediator.SourceGenerator.Implementation/Analysis/RequestMessage.cs @@ -14,8 +14,12 @@ internal sealed class RequestMessage : SymbolMetadata public bool IsStreaming => MessageType.StartsWith("Stream"); - public RequestMessage(INamedTypeSymbol symbol, INamedTypeSymbol responseSymbol, string messageType, CompilationAnalyzer analyzer) - : base(symbol, analyzer) + public RequestMessage( + INamedTypeSymbol symbol, + INamedTypeSymbol responseSymbol, + string messageType, + CompilationAnalyzer analyzer + ) : base(symbol, analyzer) { ResponseSymbol = responseSymbol; WrapperType = analyzer.RequestMessageHandlerWrappers.Single(w => w.MessageType == messageType); @@ -30,20 +34,25 @@ public RequestMessage(INamedTypeSymbol symbol, INamedTypeSymbol responseSymbol, public string HandlerWrapperTypeNameWithGenericTypeArguments => WrapperType.HandlerWrapperTypeNameWithGenericTypeArguments(Symbol, ResponseSymbol); - public string PipelineHandlerType => IsStreaming ? - $"global::Mediator.IStreamPipelineBehavior<{RequestFullName}, {ResponseFullName}>" : - $"global::Mediator.IPipelineBehavior<{RequestFullName}, {ResponseFullName}>"; + public string PipelineHandlerType => + IsStreaming + ? $"global::Mediator.IStreamPipelineBehavior<{RequestFullName}, {ResponseFullName}>" + : $"global::Mediator.IPipelineBehavior<{RequestFullName}, {ResponseFullName}>"; - public string IdentifierFullName => Symbol.GetTypeSymbolFullName(withGlobalPrefix: false, includeTypeParameters: false).Replace("global::", "").Replace('.', '_'); + public string IdentifierFullName => + Symbol + .GetTypeSymbolFullName(withGlobalPrefix: false, includeTypeParameters: false) + .Replace("global::", "") + .Replace('.', '_'); - public string HandlerWrapperPropertyName => - $"Wrapper_For_{IdentifierFullName}"; + public string HandlerWrapperPropertyName => $"Wrapper_For_{IdentifierFullName}"; public string SyncMethodName => IsStreaming ? "CreateStream" : "Send"; public string AsyncMethodName => IsStreaming ? "CreateStream" : "Send"; public string SyncReturnType => ResponseSymbol.GetTypeSymbolFullName(); - public string AsyncReturnType => IsStreaming ? - $"global::System.Collections.Generic.IAsyncEnumerable<{ResponseFullName}>" : - $"global::System.Threading.Tasks.ValueTask<{ResponseFullName}>"; + public string AsyncReturnType => + IsStreaming + ? $"global::System.Collections.Generic.IAsyncEnumerable<{ResponseFullName}>" + : $"global::System.Threading.Tasks.ValueTask<{ResponseFullName}>"; } diff --git a/src/Mediator.SourceGenerator.Implementation/Analysis/RequestMessageHandlerWrapper.cs b/src/Mediator.SourceGenerator.Implementation/Analysis/RequestMessageHandlerWrapper.cs index a60b99b..0a5ee8a 100644 --- a/src/Mediator.SourceGenerator.Implementation/Analysis/RequestMessageHandlerWrapper.cs +++ b/src/Mediator.SourceGenerator.Implementation/Analysis/RequestMessageHandlerWrapper.cs @@ -13,23 +13,23 @@ public RequestMessageHandlerWrapper(string messageType, CompilationAnalyzer anal _analyzer = analyzer; } - public string FullNamespace => - $"global::{_analyzer.MediatorNamespace}"; + public string FullNamespace => $"global::{_analyzer.MediatorNamespace}"; public string HandlerWrapperTypeName(TypeKind type) => $"{MessageType}{(type == TypeKind.Struct ? "Struct" : "Class")}HandlerWrapper"; - public string HandlerWrapperTypeFullName(TypeKind type) => - $"{FullNamespace}.{HandlerWrapperTypeName(type)}"; + public string HandlerWrapperTypeFullName(TypeKind type) => $"{FullNamespace}.{HandlerWrapperTypeName(type)}"; public string HandlerWrapperTypeNameWithGenericTypeArguments(TypeKind type) => $"{HandlerWrapperTypeName(type)}"; - public string HandlerWrapperTypeNameWithGenericTypeArguments(INamedTypeSymbol requestSymbol, INamedTypeSymbol responseSymbol) => + public string HandlerWrapperTypeNameWithGenericTypeArguments( + INamedTypeSymbol requestSymbol, + INamedTypeSymbol responseSymbol + ) => $"{HandlerWrapperTypeFullName(requestSymbol.TypeKind)}<{requestSymbol.GetTypeSymbolFullName()}, {responseSymbol.GetTypeSymbolFullName()}>"; - public string HandlerWrapperTypeOfExpression(TypeKind type) => - $"typeof({HandlerWrapperTypeFullName(type)}<,>)"; + public string HandlerWrapperTypeOfExpression(TypeKind type) => $"typeof({HandlerWrapperTypeFullName(type)}<,>)"; public string ClassHandlerWrapperTypeNameWithGenericTypeArguments => HandlerWrapperTypeNameWithGenericTypeArguments(TypeKind.Class); @@ -37,20 +37,24 @@ public string HandlerWrapperTypeOfExpression(TypeKind type) => public string StructHandlerWrapperTypeNameWithGenericTypeArguments => HandlerWrapperTypeNameWithGenericTypeArguments(TypeKind.Struct); - public string ClassHandlerWrapperTypeName => - HandlerWrapperTypeName(TypeKind.Class); + public string ClassHandlerWrapperTypeName => HandlerWrapperTypeName(TypeKind.Class); - public string StructHandlerWrapperTypeName => - HandlerWrapperTypeName(TypeKind.Struct); + public string StructHandlerWrapperTypeName => HandlerWrapperTypeName(TypeKind.Struct); public bool IsStreaming => MessageType.StartsWith("Stream"); - public string MessageHandlerDelegateName => IsStreaming ? $"global::Mediator.StreamHandlerDelegate" : - $"global::Mediator.MessageHandlerDelegate"; + public string MessageHandlerDelegateName => + IsStreaming + ? $"global::Mediator.StreamHandlerDelegate" + : $"global::Mediator.MessageHandlerDelegate"; - public string PipelineHandlerTypeName => IsStreaming ? "global::Mediator.IStreamPipelineBehavior" : - "global::Mediator.IPipelineBehavior"; + public string PipelineHandlerTypeName => + IsStreaming + ? "global::Mediator.IStreamPipelineBehavior" + : "global::Mediator.IPipelineBehavior"; - public string ReturnTypeName => IsStreaming ? "global::System.Collections.Generic.IAsyncEnumerable" : - "global::System.Threading.Tasks.ValueTask"; + public string ReturnTypeName => + IsStreaming + ? "global::System.Collections.Generic.IAsyncEnumerable" + : "global::System.Threading.Tasks.ValueTask"; } diff --git a/src/Mediator.SourceGenerator.Implementation/Analysis/SymbolMetadata.cs b/src/Mediator.SourceGenerator.Implementation/Analysis/SymbolMetadata.cs index bfb7326..4d18357 100644 --- a/src/Mediator.SourceGenerator.Implementation/Analysis/SymbolMetadata.cs +++ b/src/Mediator.SourceGenerator.Implementation/Analysis/SymbolMetadata.cs @@ -1,7 +1,6 @@ namespace Mediator.SourceGenerator; -internal abstract class SymbolMetadata : IEquatable - where T : SymbolMetadata +internal abstract class SymbolMetadata : IEquatable where T : SymbolMetadata { private static readonly SymbolEqualityComparer _comparer = SymbolEqualityComparer.Default; public readonly INamedTypeSymbol Symbol; diff --git a/src/Mediator.SourceGenerator.Implementation/Diagnostics.cs b/src/Mediator.SourceGenerator.Implementation/Diagnostics.cs index 19f2498..d28e2da 100644 --- a/src/Mediator.SourceGenerator.Implementation/Diagnostics.cs +++ b/src/Mediator.SourceGenerator.Implementation/Diagnostics.cs @@ -21,7 +21,8 @@ static Diagnostics() $"{nameof(MediatorGenerator)} got unknown error: " + "{0}", nameof(MediatorGenerator), DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); MultipleHandlersError = new DiagnosticDescriptor( GetNextId(), @@ -29,7 +30,8 @@ static Diagnostics() $"{nameof(MediatorGenerator)} found multiple handlers " + "of message type {0}", nameof(MediatorGenerator), DiagnosticSeverity.Warning, - isEnabledByDefault: true); + isEnabledByDefault: true + ); InvalidHandlerTypeError = new DiagnosticDescriptor( GetNextId(), @@ -37,15 +39,18 @@ static Diagnostics() $"{nameof(MediatorGenerator)} found invalid handler type " + "{0}", nameof(MediatorGenerator), DiagnosticSeverity.Warning, - isEnabledByDefault: true); + isEnabledByDefault: true + ); OpenGenericRequestHandler = new DiagnosticDescriptor( GetNextId(), $"{nameof(MediatorGenerator)} invalid handler", - $"{nameof(MediatorGenerator)} found invalid handler type, request/query/command handlers cannot be generic: " + "{0}", + $"{nameof(MediatorGenerator)} found invalid handler type, request/query/command handlers cannot be generic: " + + "{0}", nameof(MediatorGenerator), DiagnosticSeverity.Warning, - isEnabledByDefault: true); + isEnabledByDefault: true + ); MessageDerivesFromMultipleMessageInterfaces = new DiagnosticDescriptor( GetNextId(), @@ -53,7 +58,8 @@ static Diagnostics() $"{nameof(MediatorGenerator)} found message that derives from multiple message interfaces: " + "{0}", nameof(MediatorGenerator), DiagnosticSeverity.Warning, - isEnabledByDefault: true); + isEnabledByDefault: true + ); MessageWithoutHandler = new DiagnosticDescriptor( GetNextId(), @@ -61,7 +67,8 @@ static Diagnostics() $"{nameof(MediatorGenerator)} found message without any registered handler: " + "{0}", nameof(MediatorGenerator), DiagnosticSeverity.Warning, - isEnabledByDefault: true); + isEnabledByDefault: true + ); ConflictingConfiguration = new DiagnosticDescriptor( GetNextId(), @@ -69,7 +76,8 @@ static Diagnostics() $"{nameof(MediatorGenerator)} found conflicting configuration - both MediatorOptions and MediatorOptionsAttribute configuration are being used.", nameof(MediatorGenerator), DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); InvalidCodeBasedConfiguration = new DiagnosticDescriptor( GetNextId(), @@ -77,7 +85,8 @@ static Diagnostics() $"{nameof(MediatorGenerator)} cannot parse MediatorOptions-based configuration. Only compile-time constant values can be used in MediatorOptions configuration.", nameof(MediatorGenerator), DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); RequiredSymbolNotFound = new DiagnosticDescriptor( GetNextId(), @@ -85,7 +94,8 @@ static Diagnostics() $"{nameof(MediatorGenerator)} could not find symbol required during analysis: {0}", nameof(MediatorGenerator), DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); static string GetNextId() { @@ -101,8 +111,7 @@ private static Diagnostic Report( this CompilationAnalyzerContext context, DiagnosticDescriptor diagnosticDescriptor, T arg - ) - where T : class + ) where T : class { Diagnostic diagnostic; if (arg is ISymbol symbolArg) @@ -119,10 +128,7 @@ T arg return diagnostic; } - private static Diagnostic Report( - this CompilationAnalyzerContext context, - DiagnosticDescriptor diagnosticDescriptor - ) + private static Diagnostic Report(this CompilationAnalyzerContext context, DiagnosticDescriptor diagnosticDescriptor) { var diagnostic = Diagnostic.Create(diagnosticDescriptor, Location.None); context.ReportDiagnostic(diagnostic); @@ -130,38 +136,57 @@ DiagnosticDescriptor diagnosticDescriptor } public static readonly DiagnosticDescriptor GenericError; + internal static Diagnostic ReportGenericError(this CompilationAnalyzerContext context, Exception exception) => context.Report(GenericError, exception); public static readonly DiagnosticDescriptor MultipleHandlersError; - internal static Diagnostic ReportMultipleHandlers(this CompilationAnalyzerContext context, INamedTypeSymbol messageType) => - context.Report(MultipleHandlersError, messageType); + + internal static Diagnostic ReportMultipleHandlers( + this CompilationAnalyzerContext context, + INamedTypeSymbol messageType + ) => context.Report(MultipleHandlersError, messageType); public static readonly DiagnosticDescriptor InvalidHandlerTypeError; - internal static Diagnostic ReportInvalidHandlerType(this CompilationAnalyzerContext context, INamedTypeSymbol handlerType) => - context.Report(InvalidHandlerTypeError, handlerType); + + internal static Diagnostic ReportInvalidHandlerType( + this CompilationAnalyzerContext context, + INamedTypeSymbol handlerType + ) => context.Report(InvalidHandlerTypeError, handlerType); public static readonly DiagnosticDescriptor OpenGenericRequestHandler; - internal static Diagnostic ReportOpenGenericRequestHandler(this CompilationAnalyzerContext context, INamedTypeSymbol handlerType) => - context.Report(OpenGenericRequestHandler, handlerType); + + internal static Diagnostic ReportOpenGenericRequestHandler( + this CompilationAnalyzerContext context, + INamedTypeSymbol handlerType + ) => context.Report(OpenGenericRequestHandler, handlerType); public static readonly DiagnosticDescriptor MessageDerivesFromMultipleMessageInterfaces; - internal static Diagnostic ReportMessageDerivesFromMultipleMessageInterfaces(this CompilationAnalyzerContext context, INamedTypeSymbol messageType) => - context.Report(MessageDerivesFromMultipleMessageInterfaces, messageType); + + internal static Diagnostic ReportMessageDerivesFromMultipleMessageInterfaces( + this CompilationAnalyzerContext context, + INamedTypeSymbol messageType + ) => context.Report(MessageDerivesFromMultipleMessageInterfaces, messageType); public static readonly DiagnosticDescriptor MessageWithoutHandler; - internal static Diagnostic ReportMessageWithoutHandler(this CompilationAnalyzerContext context, INamedTypeSymbol messageType) => - context.Report(MessageWithoutHandler, messageType); + + internal static Diagnostic ReportMessageWithoutHandler( + this CompilationAnalyzerContext context, + INamedTypeSymbol messageType + ) => context.Report(MessageWithoutHandler, messageType); public static readonly DiagnosticDescriptor ConflictingConfiguration; + internal static Diagnostic ReportConflictingConfiguration(this CompilationAnalyzerContext context) => context.Report(ConflictingConfiguration); public static readonly DiagnosticDescriptor InvalidCodeBasedConfiguration; + internal static Diagnostic ReportInvalidCodeBasedConfiguration(this CompilationAnalyzerContext context) => context.Report(InvalidCodeBasedConfiguration); public static readonly DiagnosticDescriptor RequiredSymbolNotFound; + internal static Diagnostic ReportRequiredSymbolNotFound(this CompilationAnalyzerContext context, string name) => context.Report(RequiredSymbolNotFound, name); } diff --git a/src/Mediator.SourceGenerator.Implementation/EmbeddedResource.cs b/src/Mediator.SourceGenerator.Implementation/EmbeddedResource.cs index c417da6..b2a7839 100644 --- a/src/Mediator.SourceGenerator.Implementation/EmbeddedResource.cs +++ b/src/Mediator.SourceGenerator.Implementation/EmbeddedResource.cs @@ -20,17 +20,22 @@ public static string GetContent(string relativePath) .Replace(Path.DirectorySeparatorChar, '.') .Replace(Path.AltDirectorySeparatorChar, '.'); - var manifestResourceName = Assembly.GetExecutingAssembly() - .GetManifestResourceNames().FirstOrDefault(x => x!.EndsWith(resourceName, StringComparison.InvariantCulture)); + var manifestResourceName = Assembly + .GetExecutingAssembly() + .GetManifestResourceNames() + .FirstOrDefault(x => x!.EndsWith(resourceName, StringComparison.InvariantCulture)); if (string.IsNullOrEmpty(manifestResourceName)) - throw new InvalidOperationException($"Did not find required resource ending in '{resourceName}' in assembly '{baseName}'."); + throw new InvalidOperationException( + $"Did not find required resource ending in '{resourceName}' in assembly '{baseName}'." + ); - using var stream = Assembly.GetExecutingAssembly() - .GetManifestResourceStream(manifestResourceName); + using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(manifestResourceName); if (stream == null) - throw new InvalidOperationException($"Did not find required resource '{manifestResourceName}' in assembly '{baseName}'."); + throw new InvalidOperationException( + $"Did not find required resource '{manifestResourceName}' in assembly '{baseName}'." + ); using var reader = new StreamReader(stream); return reader.ReadToEnd(); diff --git a/src/Mediator.SourceGenerator.Implementation/Extensions/IsExternalInit.cs b/src/Mediator.SourceGenerator.Implementation/Extensions/IsExternalInit.cs index aabfe96..df23ad5 100644 --- a/src/Mediator.SourceGenerator.Implementation/Extensions/IsExternalInit.cs +++ b/src/Mediator.SourceGenerator.Implementation/Extensions/IsExternalInit.cs @@ -7,7 +7,5 @@ namespace System.Runtime.CompilerServices /// This class should not be used by developers in source code. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal static class IsExternalInit - { - } + internal static class IsExternalInit { } } diff --git a/src/Mediator.SourceGenerator.Implementation/Extensions/RoslynExtensions.cs b/src/Mediator.SourceGenerator.Implementation/Extensions/RoslynExtensions.cs index cbc89e7..9beeb78 100644 --- a/src/Mediator.SourceGenerator.Implementation/Extensions/RoslynExtensions.cs +++ b/src/Mediator.SourceGenerator.Implementation/Extensions/RoslynExtensions.cs @@ -2,14 +2,24 @@ namespace Mediator.SourceGenerator.Extensions; public static class RoslynExtensions { - public static string GetTypeSymbolFullName(this ITypeSymbol symbol, bool withGlobalPrefix = true, bool includeTypeParameters = true) + public static string GetTypeSymbolFullName( + this ITypeSymbol symbol, + bool withGlobalPrefix = true, + bool includeTypeParameters = true + ) { - return symbol.ToDisplayString(new SymbolDisplayFormat( - withGlobalPrefix ? SymbolDisplayGlobalNamespaceStyle.Included : SymbolDisplayGlobalNamespaceStyle.Omitted, - SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, - includeTypeParameters ? SymbolDisplayGenericsOptions.IncludeTypeParameters : SymbolDisplayGenericsOptions.None, - miscellaneousOptions: SymbolDisplayMiscellaneousOptions.ExpandNullable - )); + return symbol.ToDisplayString( + new SymbolDisplayFormat( + withGlobalPrefix + ? SymbolDisplayGlobalNamespaceStyle.Included + : SymbolDisplayGlobalNamespaceStyle.Omitted, + SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, + includeTypeParameters + ? SymbolDisplayGenericsOptions.IncludeTypeParameters + : SymbolDisplayGenericsOptions.None, + miscellaneousOptions: SymbolDisplayMiscellaneousOptions.ExpandNullable + ) + ); } public static string GetFieldSymbolFullName(this IFieldSymbol symbol) diff --git a/src/Mediator.SourceGenerator.Implementation/MediatorGenerationContext.cs b/src/Mediator.SourceGenerator.Implementation/MediatorGenerationContext.cs index 45f8d09..4973d7b 100644 --- a/src/Mediator.SourceGenerator.Implementation/MediatorGenerationContext.cs +++ b/src/Mediator.SourceGenerator.Implementation/MediatorGenerationContext.cs @@ -6,7 +6,11 @@ internal readonly struct MediatorGenerationContext public readonly IEnumerable HandlerTypes; public readonly string MediatorNamespace; - public MediatorGenerationContext(IReadOnlyDictionary> handlerMap, IEnumerable handlerTypes, string mediatorNamespace) + public MediatorGenerationContext( + IReadOnlyDictionary> handlerMap, + IEnumerable handlerTypes, + string mediatorNamespace + ) { HandlerMap = handlerMap; HandlerTypes = handlerTypes; diff --git a/src/Mediator.SourceGenerator.Roslyn38/MediatorGenerator.cs b/src/Mediator.SourceGenerator.Roslyn38/MediatorGenerator.cs index 513842d..f28b20d 100644 --- a/src/Mediator.SourceGenerator.Roslyn38/MediatorGenerator.cs +++ b/src/Mediator.SourceGenerator.Roslyn38/MediatorGenerator.cs @@ -7,7 +7,10 @@ public sealed class MediatorGenerator : ISourceGenerator public void Execute(GeneratorExecutionContext context) { - var debugOptionExists = context.AnalyzerConfigOptions.GlobalOptions.TryGetValue("build_property.Mediator_AttachDebugger", out _); + var debugOptionExists = context.AnalyzerConfigOptions.GlobalOptions.TryGetValue( + "build_property.Mediator_AttachDebugger", + out _ + ); if (debugOptionExists && !System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Launch(); diff --git a/src/Mediator.SourceGenerator.Roslyn40/IncrementalMediatorGenerator.cs b/src/Mediator.SourceGenerator.Roslyn40/IncrementalMediatorGenerator.cs index 57d0235..00b590a 100644 --- a/src/Mediator.SourceGenerator.Roslyn40/IncrementalMediatorGenerator.cs +++ b/src/Mediator.SourceGenerator.Roslyn40/IncrementalMediatorGenerator.cs @@ -13,7 +13,6 @@ private void ExecuteInternal( IReadOnlyList addMediatorCalls ) { - var generatorVersion = Versioning.GetVersion(); var analyzerContext = new CompilationAnalyzerContext( @@ -39,12 +38,14 @@ public void Initialize(IncrementalGeneratorInitializationContext context) { //System.Diagnostics.Debugger.Launch(); - context.RegisterPostInitializationOutput(context => - { - var generatorVersion = Versioning.GetVersion(); + context.RegisterPostInitializationOutput( + context => + { + var generatorVersion = Versioning.GetVersion(); - MediatorOptionsGenerator.Generate(context.AddSource, generatorVersion); - }); + MediatorOptionsGenerator.Generate(context.AddSource, generatorVersion); + } + ); var compilationProvider = context.CompilationProvider; var addMediatorCalls = context.SyntaxProvider.CreateSyntaxProvider( @@ -55,9 +56,12 @@ public void Initialize(IncrementalGeneratorInitializationContext context) IncrementalValueProvider<(Compilation Compilation, ImmutableArray AddMediatorCalls)> source = compilationProvider.Combine(addMediatorCalls.Collect()); - context.RegisterSourceOutput(source, (context, source) => - { - ExecuteInternal(in context, source.Compilation, source.AddMediatorCalls); - }); + context.RegisterSourceOutput( + source, + (context, source) => + { + ExecuteInternal(in context, source.Compilation, source.AddMediatorCalls); + } + ); } } diff --git a/src/Mediator/Handlers/ICommandHandler.cs b/src/Mediator/Handlers/ICommandHandler.cs index 18c0820..e6b3eb1 100644 --- a/src/Mediator/Handlers/ICommandHandler.cs +++ b/src/Mediator/Handlers/ICommandHandler.cs @@ -1,12 +1,8 @@ namespace Mediator; -public interface ICommandHandler - where TCommand : ICommand +public interface ICommandHandler where TCommand : ICommand { ValueTask Handle(TCommand command, CancellationToken cancellationToken); } -public interface ICommandHandler : ICommandHandler - where TCommand : ICommand -{ -} +public interface ICommandHandler : ICommandHandler where TCommand : ICommand { } diff --git a/src/Mediator/Handlers/INotificationHandler.cs b/src/Mediator/Handlers/INotificationHandler.cs index f493176..c1e8cc1 100644 --- a/src/Mediator/Handlers/INotificationHandler.cs +++ b/src/Mediator/Handlers/INotificationHandler.cs @@ -1,7 +1,6 @@ namespace Mediator; -public interface INotificationHandler - where TNotification : INotification +public interface INotificationHandler where TNotification : INotification { ValueTask Handle(TNotification notification, CancellationToken cancellationToken); } diff --git a/src/Mediator/Handlers/IQueryHandler.cs b/src/Mediator/Handlers/IQueryHandler.cs index efbba8f..338108e 100644 --- a/src/Mediator/Handlers/IQueryHandler.cs +++ b/src/Mediator/Handlers/IQueryHandler.cs @@ -1,7 +1,6 @@ namespace Mediator; -public interface IQueryHandler - where TQuery : IQuery +public interface IQueryHandler where TQuery : IQuery { ValueTask Handle(TQuery query, CancellationToken cancellationToken); } diff --git a/src/Mediator/Handlers/IRequestHandler.cs b/src/Mediator/Handlers/IRequestHandler.cs index 2c8dcbf..fbfb77a 100644 --- a/src/Mediator/Handlers/IRequestHandler.cs +++ b/src/Mediator/Handlers/IRequestHandler.cs @@ -1,12 +1,8 @@ namespace Mediator; -public interface IRequestHandler - where TRequest : IRequest +public interface IRequestHandler where TRequest : IRequest { ValueTask Handle(TRequest request, CancellationToken cancellationToken); } -public interface IRequestHandler : IRequestHandler - where TRequest : IRequest -{ -} +public interface IRequestHandler : IRequestHandler where TRequest : IRequest { } diff --git a/src/Mediator/Handlers/IStreamCommandHandler.cs b/src/Mediator/Handlers/IStreamCommandHandler.cs index e16ed94..d744802 100644 --- a/src/Mediator/Handlers/IStreamCommandHandler.cs +++ b/src/Mediator/Handlers/IStreamCommandHandler.cs @@ -1,7 +1,6 @@ namespace Mediator; -public interface IStreamCommandHandler - where TCommand : IStreamCommand +public interface IStreamCommandHandler where TCommand : IStreamCommand { IAsyncEnumerable Handle(TCommand command, CancellationToken cancellationToken); } diff --git a/src/Mediator/Handlers/IStreamQueryHandler.cs b/src/Mediator/Handlers/IStreamQueryHandler.cs index 86353cf..7d85992 100644 --- a/src/Mediator/Handlers/IStreamQueryHandler.cs +++ b/src/Mediator/Handlers/IStreamQueryHandler.cs @@ -1,7 +1,6 @@ namespace Mediator; -public interface IStreamQueryHandler - where TQuery : IStreamQuery +public interface IStreamQueryHandler where TQuery : IStreamQuery { IAsyncEnumerable Handle(TQuery query, CancellationToken cancellationToken); } diff --git a/src/Mediator/Handlers/IStreamRequestHandler.cs b/src/Mediator/Handlers/IStreamRequestHandler.cs index 972c2b4..a0e6620 100644 --- a/src/Mediator/Handlers/IStreamRequestHandler.cs +++ b/src/Mediator/Handlers/IStreamRequestHandler.cs @@ -1,7 +1,6 @@ namespace Mediator; -public interface IStreamRequestHandler - where TRequest : IStreamRequest +public interface IStreamRequestHandler where TRequest : IStreamRequest { IAsyncEnumerable Handle(TRequest request, CancellationToken cancellationToken); } diff --git a/src/Mediator/IMediator.cs b/src/Mediator/IMediator.cs index 411729e..b511e3f 100644 --- a/src/Mediator/IMediator.cs +++ b/src/Mediator/IMediator.cs @@ -1,5 +1,3 @@ namespace Mediator; -public interface IMediator : ISender, IPublisher -{ -} +public interface IMediator : ISender, IPublisher { } diff --git a/src/Mediator/ISender.cs b/src/Mediator/ISender.cs index f872396..3c5991b 100644 --- a/src/Mediator/ISender.cs +++ b/src/Mediator/ISender.cs @@ -10,11 +10,20 @@ public interface ISender ValueTask Send(object message, CancellationToken cancellationToken = default); - IAsyncEnumerable CreateStream(IStreamQuery query, CancellationToken cancellationToken = default); - - IAsyncEnumerable CreateStream(IStreamRequest request, CancellationToken cancellationToken = default); - - IAsyncEnumerable CreateStream(IStreamCommand command, CancellationToken cancellationToken = default); + IAsyncEnumerable CreateStream( + IStreamQuery query, + CancellationToken cancellationToken = default + ); + + IAsyncEnumerable CreateStream( + IStreamRequest request, + CancellationToken cancellationToken = default + ); + + IAsyncEnumerable CreateStream( + IStreamCommand command, + CancellationToken cancellationToken = default + ); IAsyncEnumerable CreateStream(object request, CancellationToken cancellationToken = default); } diff --git a/src/Mediator/Pipeline/IPipelineBehavior.cs b/src/Mediator/Pipeline/IPipelineBehavior.cs index 3650861..b8f34c2 100644 --- a/src/Mediator/Pipeline/IPipelineBehavior.cs +++ b/src/Mediator/Pipeline/IPipelineBehavior.cs @@ -1,7 +1,10 @@ namespace Mediator; -public interface IPipelineBehavior - where TMessage : notnull, IMessage +public interface IPipelineBehavior where TMessage : notnull, IMessage { - ValueTask Handle(TMessage message, CancellationToken cancellationToken, MessageHandlerDelegate next); + ValueTask Handle( + TMessage message, + CancellationToken cancellationToken, + MessageHandlerDelegate next + ); } diff --git a/src/Mediator/Pipeline/IStreamPipelineBehavior.cs b/src/Mediator/Pipeline/IStreamPipelineBehavior.cs index 36816a4..5f91a16 100644 --- a/src/Mediator/Pipeline/IStreamPipelineBehavior.cs +++ b/src/Mediator/Pipeline/IStreamPipelineBehavior.cs @@ -1,7 +1,10 @@ namespace Mediator; -public interface IStreamPipelineBehavior - where TMessage : IStreamMessage +public interface IStreamPipelineBehavior where TMessage : IStreamMessage { - IAsyncEnumerable Handle(TMessage message, CancellationToken cancellationToken, StreamHandlerDelegate next); + IAsyncEnumerable Handle( + TMessage message, + CancellationToken cancellationToken, + StreamHandlerDelegate next + ); } diff --git a/src/Mediator/Pipeline/MessageHandlerDelegate.cs b/src/Mediator/Pipeline/MessageHandlerDelegate.cs index bdeae00..e7eb26c 100644 --- a/src/Mediator/Pipeline/MessageHandlerDelegate.cs +++ b/src/Mediator/Pipeline/MessageHandlerDelegate.cs @@ -1,4 +1,6 @@ namespace Mediator; -public delegate ValueTask MessageHandlerDelegate(TMessage message, CancellationToken cancellationToken) - where TMessage : notnull, IMessage; +public delegate ValueTask MessageHandlerDelegate( + TMessage message, + CancellationToken cancellationToken +) where TMessage : notnull, IMessage; diff --git a/src/Mediator/Pipeline/StreamHandlerDelegate.cs b/src/Mediator/Pipeline/StreamHandlerDelegate.cs index 2d8fc36..fdb28ad 100644 --- a/src/Mediator/Pipeline/StreamHandlerDelegate.cs +++ b/src/Mediator/Pipeline/StreamHandlerDelegate.cs @@ -1,4 +1,6 @@ namespace Mediator; -public delegate IAsyncEnumerable StreamHandlerDelegate(TMessage message, CancellationToken cancellationToken) - where TMessage : notnull, IStreamMessage; +public delegate IAsyncEnumerable StreamHandlerDelegate( + TMessage message, + CancellationToken cancellationToken +) where TMessage : notnull, IStreamMessage; diff --git a/test/Mediator.MemAllocationTests/NonParallelCollectionDefinitionClass.cs b/test/Mediator.MemAllocationTests/NonParallelCollectionDefinitionClass.cs index 1ba952c..c02424a 100644 --- a/test/Mediator.MemAllocationTests/NonParallelCollectionDefinitionClass.cs +++ b/test/Mediator.MemAllocationTests/NonParallelCollectionDefinitionClass.cs @@ -1,6 +1,4 @@ namespace Mediator.Tests; [CollectionDefinition("Non-Parallel", DisableParallelization = true)] -public class NonParallelCollectionDefinitionClass -{ -} +public class NonParallelCollectionDefinitionClass { } diff --git a/test/Mediator.MemAllocationTests/RequestTests.cs b/test/Mediator.MemAllocationTests/RequestTests.cs index 92216a3..44af851 100644 --- a/test/Mediator.MemAllocationTests/RequestTests.cs +++ b/test/Mediator.MemAllocationTests/RequestTests.cs @@ -53,22 +53,23 @@ public async Task Test_Request_Handler_dotMemory() var afterBytes = GC.GetAllocatedBytesForCurrentThread(); Assert.Equal(0, afterBytes - beforeBytes); - dotMemory.Check(memory => - { - var traffic = memory.GetDifference(checkpoint); - var newObjects = traffic.GetNewObjects(); - foreach (var obj in newObjects.GroupByType()) - _output.WriteLine($"Allocations for {obj.TypeFullyQualifiedName}: {obj.SizeInBytes} bytes"); - - //_output.WriteLine($"Allocated: {traffic.AllocatedMemory.SizeInBytes}"); - //foreach (var obj in traffic.GroupByType()) - // _output.WriteLine($"Allocations for {obj.TypeFullyQualifiedName}: {obj.AllocatedMemoryInfo.SizeInBytes}"); - - Assert.Equal(0, traffic.GetNewObjects().ObjectsCount); - }); + dotMemory.Check( + memory => + { + var traffic = memory.GetDifference(checkpoint); + var newObjects = traffic.GetNewObjects(); + foreach (var obj in newObjects.GroupByType()) + _output.WriteLine($"Allocations for {obj.TypeFullyQualifiedName}: {obj.SizeInBytes} bytes"); + + //_output.WriteLine($"Allocated: {traffic.AllocatedMemory.SizeInBytes}"); + //foreach (var obj in traffic.GroupByType()) + // _output.WriteLine($"Allocations for {obj.TypeFullyQualifiedName}: {obj.AllocatedMemoryInfo.SizeInBytes}"); + + Assert.Equal(0, traffic.GetNewObjects().ObjectsCount); + } + ); } - [Fact] public void Test_Request_Handler() { diff --git a/test/Mediator.MemAllocationTests/SomeNotificationMemAllocTracking.cs b/test/Mediator.MemAllocationTests/SomeNotificationMemAllocTracking.cs index acde029..bd7d3d2 100644 --- a/test/Mediator.MemAllocationTests/SomeNotificationMemAllocTracking.cs +++ b/test/Mediator.MemAllocationTests/SomeNotificationMemAllocTracking.cs @@ -4,5 +4,6 @@ public sealed record SomeNotificationMemAllocTracking(Guid Id) : INotification; public sealed class SomeNotificationMemAllocTrackingHandler : INotificationHandler { - public ValueTask Handle(SomeNotificationMemAllocTracking notification, CancellationToken cancellationToken) => default; + public ValueTask Handle(SomeNotificationMemAllocTracking notification, CancellationToken cancellationToken) => + default; } diff --git a/test/Mediator.SmokeTestConsole/Program.cs b/test/Mediator.SmokeTestConsole/Program.cs index 638b826..40d881a 100644 --- a/test/Mediator.SmokeTestConsole/Program.cs +++ b/test/Mediator.SmokeTestConsole/Program.cs @@ -6,18 +6,24 @@ using LazyDICache = Mediator.Mediator.FastLazyValue; await Host.CreateDefaultBuilder() - .ConfigureLogging((context, logging) => - { - logging.ClearProviders(); - logging.AddSimpleConsole(options => + .ConfigureLogging( + (context, logging) => { - options.SingleLine = true; - }); - }) - .ConfigureServices(services => - { - services.AddHostedService(); - }) + logging.ClearProviders(); + logging.AddSimpleConsole( + options => + { + options.SingleLine = true; + } + ); + } + ) + .ConfigureServices( + services => + { + services.AddHostedService(); + } + ) .Build() .RunAsync(); @@ -35,9 +41,9 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) const int maxIterations = 1_000_000; Console.WriteLine( - $"Starting smoketests - " + - $"{nameof(concurrency)}={concurrency}" + - $", {nameof(maxIterations)}={maxIterations}" + $"Starting smoketests - " + + $"{nameof(concurrency)}={concurrency}" + + $", {nameof(maxIterations)}={maxIterations}" ); while (!stoppingToken.IsCancellationRequested && iteration < maxIterations) @@ -59,23 +65,23 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) var lastHandlers = values.Select(v => v.Cache.Wrapper_For_Request5).ToArray(); var lastHandler = lastHandlers[0]; - var hasInvalidHandler = firstHandlers.Any(h => !ReferenceEquals(h, firstHandler)) || - lastHandlers.Any(h => !ReferenceEquals(h, lastHandler)); + var hasInvalidHandler = + firstHandlers.Any(h => !ReferenceEquals(h, firstHandler)) + || lastHandlers.Any(h => !ReferenceEquals(h, lastHandler)); var hasInvalid = states.Any(s => s == LazyDICache.INVALID); var wasUninitCount = states.Count(s => s == LazyDICache.UNINIT); var wasInitingCount = states.Count(s => s == LazyDICache.INITING); var wasInitedCount = states.Count(s => s == LazyDICache.INITD); var wasCachedCount = states.Count(s => s == LazyDICache.CACHED); - Console.WriteLine( - $"Ran smoketest iteration {++iteration} - " + - $"{nameof(hasInvalidHandler)}={hasInvalidHandler}" + - $", {nameof(hasInvalid)}={hasInvalid}" + - $", {nameof(wasUninitCount)}={wasUninitCount}" + - $", {nameof(wasInitingCount)}={wasInitingCount}" + - $", {nameof(wasInitedCount)}={wasInitedCount}" + - $", {nameof(wasCachedCount)}={wasCachedCount}" + $"Ran smoketest iteration {++iteration} - " + + $"{nameof(hasInvalidHandler)}={hasInvalidHandler}" + + $", {nameof(hasInvalid)}={hasInvalid}" + + $", {nameof(wasUninitCount)}={wasUninitCount}" + + $", {nameof(wasInitingCount)}={wasInitingCount}" + + $", {nameof(wasInitedCount)}={wasInitedCount}" + + $", {nameof(wasCachedCount)}={wasCachedCount}" ); if (hasInvalidHandler || hasInvalid || wasUninitCount != 1) @@ -94,37 +100,41 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) Console.WriteLine("------------------"); Console.WriteLine( - $"Done smoketesting! - " + - $"{nameof(concurrency)}={concurrency}, {nameof(maxIterations)}={maxIterations}" + $"Done smoketesting! - " + $"{nameof(concurrency)}={concurrency}, {nameof(maxIterations)}={maxIterations}" ); } } public sealed record Request() : IRequest; + public sealed class RequestHandler : IRequestHandler { public ValueTask Handle(Request request, CancellationToken cancellationToken) => default; } public sealed record Request2() : IRequest; + public sealed class Request2Handler : IRequestHandler { public ValueTask Handle(Request2 request, CancellationToken cancellationToken) => default; } public sealed record Request3() : IRequest; + public sealed class Request3Handler : IRequestHandler { public ValueTask Handle(Request3 request, CancellationToken cancellationToken) => default; } public sealed record Request4() : IRequest; + public sealed class Request4Handler : IRequestHandler { public ValueTask Handle(Request4 request, CancellationToken cancellationToken) => default; } public sealed record Request5() : IRequest; + public sealed class Request5Handler : IRequestHandler { public ValueTask Handle(Request5 request, CancellationToken cancellationToken) => default; diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/AssertExtensions.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/AssertExtensions.cs index 96683ab..b86fe67 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/AssertExtensions.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/AssertExtensions.cs @@ -11,7 +11,11 @@ public static void AssertGen(this Compilation inputCompilation, params Action - AppDomain.CurrentDomain.GetAssemblies() + AppDomain.CurrentDomain + .GetAssemblies() .Concat(ImportantAssemblies) .Distinct() .Where(a => !a.IsDynamic) @@ -26,7 +27,7 @@ public static class Fixture public static Compilation CreateLibrary(params string[] source) { var references = new List(); - var assemblies = AssemblyReferencesForCodegen;; + var assemblies = AssemblyReferencesForCodegen; foreach (Assembly assembly in assemblies) { if (!assembly.IsDynamic) @@ -39,13 +40,12 @@ public static Compilation CreateLibrary(params string[] source) "compilation", source.Select(s => CSharpSyntaxTree.ParseText(s)).ToArray(), references, - new CSharpCompilationOptions( - OutputKind.DynamicallyLinkedLibrary - ) + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) ); return compilation; } - public static Task SourceFromResourceFile(string file) => File.ReadAllTextAsync(Path.Combine("resources", file)); + public static Task SourceFromResourceFile(string file) => + File.ReadAllTextAsync(Path.Combine("resources", file)); } diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/GeneratorResult.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/GeneratorResult.cs index 77dba25..3a2a076 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/GeneratorResult.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/GeneratorResult.cs @@ -3,4 +3,9 @@ namespace Mediator.SourceGenerator.Tests; -public sealed record GeneratorResult(MediatorGenerator Generator, ImmutableArray Diagnostics, GeneratorDriverRunResult RunResult, Compilation OutputCompilation); +public sealed record GeneratorResult( + MediatorGenerator Generator, + ImmutableArray Diagnostics, + GeneratorDriverRunResult RunResult, + Compilation OutputCompilation +); diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/LifetimeOptionTests.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/LifetimeOptionTests.cs index 1df4b66..9fb4a75 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/LifetimeOptionTests.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/LifetimeOptionTests.cs @@ -5,7 +5,8 @@ public sealed class LifetimeOptionTests [Fact] public void Test_No_Args() { - var source = @" + var source = + @" using Mediator; using Microsoft.Extensions.DependencyInjection; @@ -37,7 +38,8 @@ public static void Main() [Fact] public void Test_Transient_Lifetime_With_Named_Namespace_Arg() { - var source = @" + var source = + @" using Mediator; using Microsoft.Extensions.DependencyInjection; diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/ReportingTests.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/ReportingTests.cs index 3f08fcc..eceb584 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/ReportingTests.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/ReportingTests.cs @@ -7,7 +7,8 @@ public sealed class ReportingTests [Fact] public void Test_Empty_Program() { - var inputCompilation = Fixture.CreateLibrary(@" + var inputCompilation = Fixture.CreateLibrary( + @" namespace MyCode { public class Program @@ -17,15 +18,16 @@ public static void Main(string[] args) } } } -"); +" + ); inputCompilation.AssertGen( Assertions.CompilesWithoutDiagnostics, result => { Assert.True(result.OutputCompilation.SyntaxTrees.Count() == 4); // Original + attribute + options + mediator impl - Assert.True(result.RunResult.GeneratedTrees.Length == 3); // attribute + options + mediator impl - } + Assert.True(result.RunResult.GeneratedTrees.Length == 3); // attribute + options + mediator impl + } ); } @@ -35,9 +37,7 @@ public async Task Test_Deep_Namespace_Program() var source = await Fixture.SourceFromResourceFile("DeepNamespaceProgram.cs"); var inputCompilation = Fixture.CreateLibrary(source); - inputCompilation.AssertGen( - Assertions.CompilesWithoutDiagnostics - ); + inputCompilation.AssertGen(Assertions.CompilesWithoutDiagnostics); } [Fact] @@ -46,9 +46,7 @@ public async Task Test_Static_Nested_Handler_Program() var source = await Fixture.SourceFromResourceFile("StaticNestedHandlerProgram.cs"); var inputCompilation = Fixture.CreateLibrary(source); - inputCompilation.AssertGen( - Assertions.CompilesWithoutDiagnostics - ); + inputCompilation.AssertGen(Assertions.CompilesWithoutDiagnostics); } [Fact] @@ -141,9 +139,7 @@ public async Task Test_No_Messages_Program() var source = await Fixture.SourceFromResourceFile("NoMessagesProgram.cs"); var inputCompilation = Fixture.CreateLibrary(source); - inputCompilation.AssertGen( - Assertions.CompilesWithoutDiagnostics - ); + inputCompilation.AssertGen(Assertions.CompilesWithoutDiagnostics); } [Fact] @@ -152,9 +148,7 @@ public async Task Test_Null_Namespace_Variable() var source = await Fixture.SourceFromResourceFile("NullNamespaceVariable.cs"); var inputCompilation = Fixture.CreateLibrary(source); - inputCompilation.AssertGen( - Assertions.CompilesWithoutDiagnostics - ); + inputCompilation.AssertGen(Assertions.CompilesWithoutDiagnostics); } [Fact] @@ -197,9 +191,7 @@ public async Task Test_Const_Variable_In_Config() var source = await Fixture.SourceFromResourceFile("ConstVariablesConfig.cs"); var inputCompilation = Fixture.CreateLibrary(source); - inputCompilation.AssertGen( - Assertions.CompilesWithoutDiagnostics - ); + inputCompilation.AssertGen(Assertions.CompilesWithoutDiagnostics); } [Fact] diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/SamplesTests.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/SamplesTests.cs index 9c070d1..b3b9db3 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/SamplesTests.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/SamplesTests.cs @@ -13,10 +13,7 @@ public async Task Test_SimpleConsole() var tester = new Verifier.Test { TestBehaviors = TestBehaviors.SkipGeneratedSourcesCheck, - TestState = - { - Sources = { source }, - }, + TestState = { Sources = { source }, }, }; await tester.RunAsync(); } @@ -29,10 +26,7 @@ public async Task Test_SimpleEndToEnd() await new Verifier.Test { TestBehaviors = TestBehaviors.SkipGeneratedSourcesCheck, - TestState = - { - Sources = { source }, - }, + TestState = { Sources = { source }, }, }.RunAsync(); } @@ -44,10 +38,7 @@ public async Task Test_SimpleStreaming() await new Verifier.Test { TestBehaviors = TestBehaviors.SkipGeneratedSourcesCheck, - TestState = - { - Sources = { source }, - }, + TestState = { Sources = { source }, }, }.RunAsync(); } } diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/SourceGenVerifier.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/SourceGenVerifier.cs index d0317bd..9a34031 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/SourceGenVerifier.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/SourceGenVerifier.cs @@ -1,4 +1,3 @@ - using Mediator.SourceGenerator.Tests; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -6,35 +5,40 @@ using Microsoft.CodeAnalysis.Testing.Verifiers; using System.Collections.Immutable; -public static class CSharpSourceGeneratorVerifier - where TSourceGenerator : ISourceGenerator, new() +public static class CSharpSourceGeneratorVerifier where TSourceGenerator : ISourceGenerator, new() { public class Test : CSharpSourceGeneratorTest { public Test() { - var refs = Fixture.AssemblyReferencesForCodegen - .Select(a => a.Location) - .ToImmutableArray(); + var refs = Fixture.AssemblyReferencesForCodegen.Select(a => a.Location).ToImmutableArray(); - var metadataRefs = refs - .Select(l => MetadataReference.CreateFromFile(l)) - .ToImmutableArray(); + var metadataRefs = refs.Select(l => MetadataReference.CreateFromFile(l)).ToImmutableArray(); - this.ReferenceAssemblies = Microsoft.CodeAnalysis.Testing.ReferenceAssemblies.Net.Net60 - .WithAssemblies(refs); + this.ReferenceAssemblies = Microsoft.CodeAnalysis.Testing.ReferenceAssemblies.Net.Net60.WithAssemblies( + refs + ); - this.SolutionTransforms.Add((sln, projectId) => - { - var compilationOptions = ((CSharpCompilationOptions)sln.GetProject(projectId)!.CompilationOptions!) - .WithOutputKind(OutputKind.ConsoleApplication) - .WithUsings("System", "System.Collections.Generic", "System.IO", "System.Linq", "System.Net.Http", "System.Threading", "System.Threading.Tasks"); + this.SolutionTransforms.Add( + (sln, projectId) => + { + var compilationOptions = ((CSharpCompilationOptions)sln.GetProject(projectId)!.CompilationOptions!) + .WithOutputKind(OutputKind.ConsoleApplication) + .WithUsings( + "System", + "System.Collections.Generic", + "System.IO", + "System.Linq", + "System.Net.Http", + "System.Threading", + "System.Threading.Tasks" + ); - sln = sln - .AddMetadataReferences(projectId, metadataRefs) - .WithProjectCompilationOptions(projectId, compilationOptions); - return sln; - }); + sln = sln.AddMetadataReferences(projectId, metadataRefs) + .WithProjectCompilationOptions(projectId, compilationOptions); + return sln; + } + ); } public TSourceGenerator SourceGenerator => (TSourceGenerator)GetSourceGenerators().Single(); @@ -45,7 +49,8 @@ protected override CompilationOptions CreateCompilationOptions() return compilationOptions .WithSpecificDiagnosticOptions( compilationOptions.SpecificDiagnosticOptions.SetItems(GetNullableWarningsFromCompiler()) - ).WithOutputKind(OutputKind.ConsoleApplication); + ) + .WithOutputKind(OutputKind.ConsoleApplication); } public LanguageVersion LanguageVersion { get; set; } = LanguageVersion.Latest; @@ -53,7 +58,11 @@ protected override CompilationOptions CreateCompilationOptions() private static ImmutableDictionary GetNullableWarningsFromCompiler() { string[] args = { "/warnaserror:nullable" }; - var commandLineArguments = CSharpCommandLineParser.Default.Parse(args, baseDirectory: Environment.CurrentDirectory, sdkDirectory: Environment.CurrentDirectory); + var commandLineArguments = CSharpCommandLineParser.Default.Parse( + args, + baseDirectory: Environment.CurrentDirectory, + sdkDirectory: Environment.CurrentDirectory + ); var nullableWarnings = commandLineArguments.CompilationOptions.SpecificDiagnosticOptions; return nullableWarnings; diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/ConfigurationConflictProgram.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/ConfigurationConflictProgram.cs index e41f59c..ef1c826 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/ConfigurationConflictProgram.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/ConfigurationConflictProgram.cs @@ -14,11 +14,13 @@ public static async Task Main() { var services = new ServiceCollection(); - services.AddMediator(options => - { - options.Namespace = "SimpleConsole.Mediator"; - options.ServiceLifetime = ServiceLifetime.Transient; - }); + services.AddMediator( + options => + { + options.Namespace = "SimpleConsole.Mediator"; + options.ServiceLifetime = ServiceLifetime.Transient; + } + ); var serviceProvider = services.BuildServiceProvider(); diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/ConstVariablesConfig.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/ConstVariablesConfig.cs index 02c42c6..6a0ed29 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/ConstVariablesConfig.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/ConstVariablesConfig.cs @@ -15,11 +15,13 @@ public static async Task Main() { var services = new ServiceCollection(); - services.AddMediator(options => - { - options.Namespace = MediatorNamespace; - options.ServiceLifetime = Lifetime; - }); + services.AddMediator( + options => + { + options.Namespace = MediatorNamespace; + options.ServiceLifetime = Lifetime; + } + ); var serviceProvider = services.BuildServiceProvider(); diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/IntCastLifetime.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/IntCastLifetime.cs index f8636eb..b22689b 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/IntCastLifetime.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/IntCastLifetime.cs @@ -12,10 +12,12 @@ public static async Task Main() { var services = new ServiceCollection(); - services.AddMediator(options => - { - options.ServiceLifetime = (ServiceLifetime)(int)ServiceLifetime.Transient; - }); + services.AddMediator( + options => + { + options.ServiceLifetime = (ServiceLifetime)(int)ServiceLifetime.Transient; + } + ); var serviceProvider = services.BuildServiceProvider(); diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/InvalidVariablesConfig.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/InvalidVariablesConfig.cs index 79b63bc..688bf0b 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/InvalidVariablesConfig.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/InvalidVariablesConfig.cs @@ -15,11 +15,13 @@ public static async Task Main() { var services = new ServiceCollection(); - services.AddMediator(options => - { - options.Namespace = MediatorNamespace; - options.ServiceLifetime = Lifetime; - }); + services.AddMediator( + options => + { + options.Namespace = MediatorNamespace; + options.ServiceLifetime = Lifetime; + } + ); var serviceProvider = services.BuildServiceProvider(); diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/LocalLiteralVariableConfig.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/LocalLiteralVariableConfig.cs index 4ae61e3..8c2c51f 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/LocalLiteralVariableConfig.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/LocalLiteralVariableConfig.cs @@ -15,11 +15,13 @@ public static async Task Main() var ns = "SomeNamespace"; var lifetime = ServiceLifetime.Scoped; - services.AddMediator(options => - { - options.Namespace = ns; - options.ServiceLifetime = lifetime; - }); + services.AddMediator( + options => + { + options.Namespace = ns; + options.ServiceLifetime = lifetime; + } + ); var serviceProvider = services.BuildServiceProvider(); diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/LocalVariablesReferencingConstsConfig.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/LocalVariablesReferencingConstsConfig.cs index 891e01f..6fbe6b6 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/LocalVariablesReferencingConstsConfig.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/LocalVariablesReferencingConstsConfig.cs @@ -24,11 +24,13 @@ public static async Task Main() var ns = NSStaticProp; var lifetime = LifetimeStaticProp; - services.AddMediator(options => - { - options.Namespace = ns; - options.ServiceLifetime = lifetime; - }); + services.AddMediator( + options => + { + options.Namespace = ns; + options.ServiceLifetime = lifetime; + } + ); var serviceProvider = services.BuildServiceProvider(); diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/NullNamespaceVariable.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/NullNamespaceVariable.cs index 6d6a477..e75d9b1 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/NullNamespaceVariable.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/NullNamespaceVariable.cs @@ -12,10 +12,12 @@ public static async Task Main() { var services = new ServiceCollection(); - services.AddMediator(options => - { - options.Namespace = null; - }); + services.AddMediator( + options => + { + options.Namespace = null; + } + ); var serviceProvider = services.BuildServiceProvider(); diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/StreamingProgram.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/StreamingProgram.cs index 29b7e0a..72e6049 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/StreamingProgram.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/StreamingProgram.cs @@ -42,7 +42,10 @@ public sealed record Pong(Guid Id); public sealed class PingHandler : IStreamRequestHandler { - public async IAsyncEnumerable Handle(StreamPing request, [EnumeratorCancellation] CancellationToken cancellationToken) + public async IAsyncEnumerable Handle( + StreamPing request, + [EnumeratorCancellation] CancellationToken cancellationToken + ) { for (int i = 0; i < 5; i++) { diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/UnassignedLifetimeVariableConfig.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/UnassignedLifetimeVariableConfig.cs index 18a2a16..7ec3d76 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/UnassignedLifetimeVariableConfig.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/UnassignedLifetimeVariableConfig.cs @@ -14,10 +14,12 @@ public static async Task Main() { var services = new ServiceCollection(); - services.AddMediator(options => - { - options.ServiceLifetime = Lifetime; - }); + services.AddMediator( + options => + { + options.ServiceLifetime = Lifetime; + } + ); var serviceProvider = services.BuildServiceProvider(); diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/UnassignedNamespaceVariableConfig.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/UnassignedNamespaceVariableConfig.cs index dfdc387..c80adc0 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/UnassignedNamespaceVariableConfig.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/UnassignedNamespaceVariableConfig.cs @@ -14,10 +14,12 @@ public static async Task Main() { var services = new ServiceCollection(); - services.AddMediator(options => - { - options.Namespace = MediatorNamespace; - }); + services.AddMediator( + options => + { + options.Namespace = MediatorNamespace; + } + ); var serviceProvider = services.BuildServiceProvider(); diff --git a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/UnassignedVariablesConfig.cs b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/UnassignedVariablesConfig.cs index 73a7165..e4690cd 100644 --- a/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/UnassignedVariablesConfig.cs +++ b/test/Mediator.SourceGenerator.Roslyn38.Tests/resources/UnassignedVariablesConfig.cs @@ -15,11 +15,13 @@ public static async Task Main() { var services = new ServiceCollection(); - services.AddMediator(options => - { - options.Namespace = MediatorNamespace; - options.ServiceLifetime = Lifetime; - }); + services.AddMediator( + options => + { + options.Namespace = MediatorNamespace; + options.ServiceLifetime = Lifetime; + } + ); var serviceProvider = services.BuildServiceProvider(); diff --git a/test/Mediator.Tests.ScopedLifetime/Init.cs b/test/Mediator.Tests.ScopedLifetime/Init.cs index 5e6c5cc..4de8b3d 100644 --- a/test/Mediator.Tests.ScopedLifetime/Init.cs +++ b/test/Mediator.Tests.ScopedLifetime/Init.cs @@ -7,8 +7,7 @@ namespace Mediator.Tests.ScopedLifetime; public class Framework : XunitTestFramework { - public Framework(IMessageSink messageSink) - : base(messageSink) + public Framework(IMessageSink messageSink) : base(messageSink) { Fixture.CreateServiceScope = true; } diff --git a/test/Mediator.Tests.ScopedLifetime/Options.cs b/test/Mediator.Tests.ScopedLifetime/Options.cs index 4c3470c..f8c51ca 100644 --- a/test/Mediator.Tests.ScopedLifetime/Options.cs +++ b/test/Mediator.Tests.ScopedLifetime/Options.cs @@ -1,4 +1,3 @@ - using Mediator; using Microsoft.Extensions.DependencyInjection; diff --git a/test/Mediator.Tests.TransientLifetime/Options.cs b/test/Mediator.Tests.TransientLifetime/Options.cs index 5f29423..5d5d978 100644 --- a/test/Mediator.Tests.TransientLifetime/Options.cs +++ b/test/Mediator.Tests.TransientLifetime/Options.cs @@ -1,4 +1,3 @@ - using Mediator; using Microsoft.Extensions.DependencyInjection; diff --git a/test/Mediator.Tests/AbstractRequestHandlerTests.cs b/test/Mediator.Tests/AbstractRequestHandlerTests.cs index 3e39d79..acc5372 100644 --- a/test/Mediator.Tests/AbstractRequestHandlerTests.cs +++ b/test/Mediator.Tests/AbstractRequestHandlerTests.cs @@ -9,14 +9,20 @@ public sealed record NotificationWithAbstractHandler(Guid Id) : INotification; public abstract class AbstractNotificationHandler : INotificationHandler { - public abstract ValueTask Handle(NotificationWithAbstractHandler notification, CancellationToken cancellationToken); + public abstract ValueTask Handle( + NotificationWithAbstractHandler notification, + CancellationToken cancellationToken + ); } public sealed class ConcreteNotificationHandler : AbstractNotificationHandler { internal static readonly ConcurrentBag Ids = new(); - public override ValueTask Handle(NotificationWithAbstractHandler notification, CancellationToken cancellationToken) + public override ValueTask Handle( + NotificationWithAbstractHandler notification, + CancellationToken cancellationToken + ) { Ids.Add(notification.Id); return default; @@ -27,7 +33,10 @@ public sealed class ConcreteNotificationHandler2 : AbstractNotificationHandler { internal static readonly ConcurrentBag Ids = new(); - public override ValueTask Handle(NotificationWithAbstractHandler notification, CancellationToken cancellationToken) + public override ValueTask Handle( + NotificationWithAbstractHandler notification, + CancellationToken cancellationToken + ) { Ids.Add(notification.Id); return default; diff --git a/test/Mediator.Tests/BasicHandlerTests.cs b/test/Mediator.Tests/BasicHandlerTests.cs index 6674121..e5f7cf1 100644 --- a/test/Mediator.Tests/BasicHandlerTests.cs +++ b/test/Mediator.Tests/BasicHandlerTests.cs @@ -20,7 +20,8 @@ public void Test_Get_Handlers() INotificationHandler handler1 = new SomeStructNotificationHandler(); //INotificationHandler handler2 = new CatchAllPolymorphicNotificationHandler(); - INotificationHandler handler3 = new SomeGenericConstrainedNotificationHandler(); + INotificationHandler handler3 = + new SomeGenericConstrainedNotificationHandler(); var handlers = sp.GetServices>(); Assert.NotNull(handlers); diff --git a/test/Mediator.Tests/Fixture.cs b/test/Mediator.Tests/Fixture.cs index f8d338c..f95c56f 100644 --- a/test/Mediator.Tests/Fixture.cs +++ b/test/Mediator.Tests/Fixture.cs @@ -75,15 +75,17 @@ public CustomServiceProvider(IServiceCollection services) return list; } - var descriptor = _services.FirstOrDefault(s => s.ServiceType == serviceType) ?? - _services.FirstOrDefault(s => s.ServiceType.IsAssignableTo(serviceType)); + var descriptor = + _services.FirstOrDefault(s => s.ServiceType == serviceType) + ?? _services.FirstOrDefault(s => s.ServiceType.IsAssignableTo(serviceType)); if (descriptor is null) throw new Exception("Service not found"); - var result = descriptor.ImplementationInstance ?? - descriptor.ImplementationFactory?.Invoke(this) ?? - ActivatorUtilities.CreateInstance(this, descriptor.ImplementationType!); + var result = + descriptor.ImplementationInstance + ?? descriptor.ImplementationFactory?.Invoke(this) + ?? ActivatorUtilities.CreateInstance(this, descriptor.ImplementationType!); if (result is null) throw new Exception("Service not found"); @@ -99,7 +101,11 @@ public CustomServiceProvider(IServiceCollection services) } } - private sealed class CustomServiceProviderScope : IServiceScope, IServiceProvider, IAsyncDisposable, IServiceScopeFactory + private sealed class CustomServiceProviderScope + : IServiceScope, + IServiceProvider, + IAsyncDisposable, + IServiceScopeFactory { public CustomServiceProviderScope(CustomServiceProvider provider, bool isRootScope) { @@ -123,9 +129,7 @@ public CustomServiceProviderScope(CustomServiceProvider provider, bool isRootSco public IServiceScope CreateScope() => RootProvider.CreateScope(); - public void Dispose() - { - } + public void Dispose() { } public ValueTask DisposeAsync() { diff --git a/test/Mediator.Tests/NonParallelCollectionDefinitionClass.cs b/test/Mediator.Tests/NonParallelCollectionDefinitionClass.cs index 1ba952c..c02424a 100644 --- a/test/Mediator.Tests/NonParallelCollectionDefinitionClass.cs +++ b/test/Mediator.Tests/NonParallelCollectionDefinitionClass.cs @@ -1,6 +1,4 @@ namespace Mediator.Tests; [CollectionDefinition("Non-Parallel", DisableParallelization = true)] -public class NonParallelCollectionDefinitionClass -{ -} +public class NonParallelCollectionDefinitionClass { } diff --git a/test/Mediator.Tests/OpenConstrainedGenericsTests.cs b/test/Mediator.Tests/OpenConstrainedGenericsTests.cs index 94c4b38..b192cd4 100644 --- a/test/Mediator.Tests/OpenConstrainedGenericsTests.cs +++ b/test/Mediator.Tests/OpenConstrainedGenericsTests.cs @@ -35,7 +35,11 @@ public ValueTask Handle(TNotification notification, CancellationToken cancellati public sealed class SomeGenericConstrainedPipeline : IPipelineBehavior where TRequest : IBaseRequest // Only requests, not commands or queries { - public async ValueTask Handle(TRequest message, CancellationToken cancellationToken, MessageHandlerDelegate next) + public async ValueTask Handle( + TRequest message, + CancellationToken cancellationToken, + MessageHandlerDelegate next + ) { var response = await next(message, cancellationToken); if (response is SomeResponse someResponse) @@ -53,12 +57,16 @@ public async Task Test_Constrained_Generic_Argument_Handler() var notification1 = new SomeNotification(Guid.NewGuid()); var notification2 = new SomeOtherNotification(Guid.NewGuid()); - var handler1 = (SomeGenericConstrainedNotificationHandler)sp - .GetServices>() - .Single(h => h is SomeGenericConstrainedNotificationHandler); - var handler2 = (SomeGenericConstrainedNotificationHandler)sp - .GetServices>() - .Single(h => h is SomeGenericConstrainedNotificationHandler); + var handler1 = + (SomeGenericConstrainedNotificationHandler)sp.GetServices< + INotificationHandler + >() + .Single(h => h is SomeGenericConstrainedNotificationHandler); + var handler2 = + (SomeGenericConstrainedNotificationHandler)sp.GetServices< + INotificationHandler + >() + .Single(h => h is SomeGenericConstrainedNotificationHandler); Assert.NotNull(handler1); Assert.NotNull(handler2); @@ -79,7 +87,9 @@ public async Task Test_Notification_Without_Concrete_Handler() await mediator.Publish(notification); - var handler = (CatchAllPolymorphicNotificationHandler)sp.GetRequiredService>(); + var handler = (CatchAllPolymorphicNotificationHandler)sp.GetRequiredService< + INotificationHandler + >(); Assert.NotNull(handler); Assert.Contains(notification.Id, CatchAllPolymorphicNotificationHandler.Ids); } @@ -93,7 +103,9 @@ public async Task Test_Notification_Without_Concrete_Handler_As_Objct() await mediator.Publish((object)notification); - var handler = (CatchAllPolymorphicNotificationHandler)sp.GetRequiredService>(); + var handler = (CatchAllPolymorphicNotificationHandler)sp.GetRequiredService< + INotificationHandler + >(); Assert.Contains(notification.Id, CatchAllPolymorphicNotificationHandler.Ids); Assert.NotNull(handler); } @@ -101,10 +113,12 @@ public async Task Test_Notification_Without_Concrete_Handler_As_Objct() [Fact] public async Task Test_Constrained_Generic_Argument_Pipeline() { - var (sp, mediator) = Fixture.GetMediator(services => - { - services.AddSingleton(typeof(IPipelineBehavior<,>), typeof(SomeGenericConstrainedPipeline<,>)); - }); + var (sp, mediator) = Fixture.GetMediator( + services => + { + services.AddSingleton(typeof(IPipelineBehavior<,>), typeof(SomeGenericConstrainedPipeline<,>)); + } + ); var request = new SomeRequest(Guid.NewGuid()); var command = new SomeCommand(Guid.NewGuid()); diff --git a/test/Mediator.Tests/Pipeline/CommandSpecificPipeline.cs b/test/Mediator.Tests/Pipeline/CommandSpecificPipeline.cs index ecd15e8..489fb79 100644 --- a/test/Mediator.Tests/Pipeline/CommandSpecificPipeline.cs +++ b/test/Mediator.Tests/Pipeline/CommandSpecificPipeline.cs @@ -1,12 +1,15 @@ namespace Mediator.Tests.Pipeline; -public sealed class CommandSpecificPipeline - : IPipelineBehavior +public sealed class CommandSpecificPipeline : IPipelineBehavior where TCommand : IBaseCommand { public static int CallCount { get; private set; } - public ValueTask Handle(TCommand message, CancellationToken cancellationToken, MessageHandlerDelegate next) + public ValueTask Handle( + TCommand message, + CancellationToken cancellationToken, + MessageHandlerDelegate next + ) { CallCount++; return next(message, cancellationToken); diff --git a/test/Mediator.Tests/Pipeline/GenericPipeline.cs b/test/Mediator.Tests/Pipeline/GenericPipeline.cs index 64ffba2..b15519e 100644 --- a/test/Mediator.Tests/Pipeline/GenericPipeline.cs +++ b/test/Mediator.Tests/Pipeline/GenericPipeline.cs @@ -8,8 +8,11 @@ public sealed class GenericPipelineState : IPipelineTestData public Guid Id => Message is null ? default : (Guid)Message.GetType()!.GetProperty("Id")!.GetValue(Message)!; public long LastMsgTimestamp { get; private set; } - public ValueTask Handle(TMessage message, CancellationToken cancellationToken, MessageHandlerDelegate next) - where TMessage : IMessage + public ValueTask Handle( + TMessage message, + CancellationToken cancellationToken, + MessageHandlerDelegate next + ) where TMessage : IMessage { LastMsgTimestamp = Stopwatch.GetTimestamp(); @@ -18,8 +21,11 @@ public ValueTask Handle(TMessage message, Cancel return next(message, cancellationToken); } - public IAsyncEnumerable Handle(TMessage message, CancellationToken cancellationToken, StreamHandlerDelegate next) - where TMessage : IStreamMessage + public IAsyncEnumerable Handle( + TMessage message, + CancellationToken cancellationToken, + StreamHandlerDelegate next + ) where TMessage : IStreamMessage { LastMsgTimestamp = Stopwatch.GetTimestamp(); @@ -40,12 +46,16 @@ public sealed class GenericPipeline : IPipelineBehavior _state.LastMsgTimestamp; - public ValueTask Handle(TMessage message, CancellationToken cancellationToken, MessageHandlerDelegate next) => - _state.Handle(message, cancellationToken, next); + public ValueTask Handle( + TMessage message, + CancellationToken cancellationToken, + MessageHandlerDelegate next + ) => _state.Handle(message, cancellationToken, next); } -public sealed class GenericStreamPipeline : IStreamPipelineBehavior, IPipelineTestData - where TMessage : IStreamMessage +public sealed class GenericStreamPipeline + : IStreamPipelineBehavior, + IPipelineTestData where TMessage : IStreamMessage { private readonly GenericPipelineState _state; @@ -55,6 +65,9 @@ public sealed class GenericStreamPipeline : IStreamPipeline public long LastMsgTimestamp => _state.LastMsgTimestamp; - public IAsyncEnumerable Handle(TMessage message, CancellationToken cancellationToken, StreamHandlerDelegate next) => - _state.Handle(message, cancellationToken, next); + public IAsyncEnumerable Handle( + TMessage message, + CancellationToken cancellationToken, + StreamHandlerDelegate next + ) => _state.Handle(message, cancellationToken, next); } diff --git a/test/Mediator.Tests/Pipeline/PipelineTests.cs b/test/Mediator.Tests/Pipeline/PipelineTests.cs index baf1dfa..c18e192 100644 --- a/test/Mediator.Tests/Pipeline/PipelineTests.cs +++ b/test/Mediator.Tests/Pipeline/PipelineTests.cs @@ -8,14 +8,18 @@ public sealed class PipelineTests [Fact] public async Task Test_Pipeline() { - var (sp, mediator) = Fixture.GetMediator(services => - { - services.AddSingleton, SomePipeline>(); - }); + var (sp, mediator) = Fixture.GetMediator( + services => + { + services.AddSingleton, SomePipeline>(); + } + ); var id = Guid.NewGuid(); - var pipelineStep = sp.GetServices>().Single(s => s is SomePipeline) as SomePipeline; + var pipelineStep = + sp.GetServices>().Single(s => s is SomePipeline) + as SomePipeline; Assert.NotNull(pipelineStep); var response = await mediator.Send(new SomeRequest(id)); Assert.Equal(id, response.Id); @@ -25,11 +29,13 @@ public async Task Test_Pipeline() [Fact] public async Task Test_Generic_Pipeline() { - var (sp, mediator) = Fixture.GetMediator(services => - { - services.AddSingleton(); - services.AddSingleton(typeof(IPipelineBehavior<,>), typeof(GenericPipeline<,>)); - }); + var (sp, mediator) = Fixture.GetMediator( + services => + { + services.AddSingleton(); + services.AddSingleton(typeof(IPipelineBehavior<,>), typeof(GenericPipeline<,>)); + } + ); var request = new SomeRequest(Guid.NewGuid()); var requestWithoutResponse = new SomeRequestWithoutResponse(Guid.NewGuid()); @@ -66,10 +72,12 @@ public async Task Test_Generic_Pipeline() [Fact] public async Task Test_Command_Specific_Pipeline() { - var (sp, mediator) = Fixture.GetMediator(services => - { - services.AddSingleton(typeof(IPipelineBehavior<,>), typeof(CommandSpecificPipeline<,>)); - }); + var (sp, mediator) = Fixture.GetMediator( + services => + { + services.AddSingleton(typeof(IPipelineBehavior<,>), typeof(CommandSpecificPipeline<,>)); + } + ); var id = Guid.NewGuid(); @@ -85,12 +93,14 @@ public async Task Test_Command_Specific_Pipeline() [Fact] public async Task Test_Pipeline_Ordering() { - var (sp, mediator) = Fixture.GetMediator(services => - { - services.AddSingleton(); - services.AddSingleton(typeof(IPipelineBehavior<,>), typeof(GenericPipeline<,>)); - services.AddSingleton, SomePipeline>(); - }); + var (sp, mediator) = Fixture.GetMediator( + services => + { + services.AddSingleton(); + services.AddSingleton(typeof(IPipelineBehavior<,>), typeof(GenericPipeline<,>)); + services.AddSingleton, SomePipeline>(); + } + ); var id = Guid.NewGuid(); diff --git a/test/Mediator.Tests/Pipeline/SomePipeline.cs b/test/Mediator.Tests/Pipeline/SomePipeline.cs index 03cf025..39a6e2b 100644 --- a/test/Mediator.Tests/Pipeline/SomePipeline.cs +++ b/test/Mediator.Tests/Pipeline/SomePipeline.cs @@ -8,7 +8,11 @@ public sealed class SomePipeline : IPipelineBehavior, public Guid Id { get; private set; } public long LastMsgTimestamp { get; private set; } - public ValueTask Handle(SomeRequest message, CancellationToken cancellationToken, MessageHandlerDelegate next) + public ValueTask Handle( + SomeRequest message, + CancellationToken cancellationToken, + MessageHandlerDelegate next + ) { LastMsgTimestamp = Stopwatch.GetTimestamp(); diff --git a/test/Mediator.Tests/Pipeline/StreamingPipelineTests.cs b/test/Mediator.Tests/Pipeline/StreamingPipelineTests.cs index 790e014..57b6101 100644 --- a/test/Mediator.Tests/Pipeline/StreamingPipelineTests.cs +++ b/test/Mediator.Tests/Pipeline/StreamingPipelineTests.cs @@ -8,10 +8,15 @@ public sealed class StreamingPipelineTests [Fact] public async Task Test_Pipeline() { - var (sp, mediator) = Fixture.GetMediator(services => - { - services.AddSingleton, SomeStreamingPipeline>(); - }); + var (sp, mediator) = Fixture.GetMediator( + services => + { + services.AddSingleton< + IStreamPipelineBehavior, + SomeStreamingPipeline + >(); + } + ); var id = Guid.NewGuid(); @@ -27,11 +32,13 @@ public async Task Test_Pipeline() [Fact] public async Task Test_Generic_Pipeline() { - var (sp, mediator) = Fixture.GetMediator(services => - { - services.AddSingleton(); - services.AddSingleton(typeof(IStreamPipelineBehavior<,>), typeof(GenericStreamPipeline<,>)); - }); + var (sp, mediator) = Fixture.GetMediator( + services => + { + services.AddSingleton(); + services.AddSingleton(typeof(IStreamPipelineBehavior<,>), typeof(GenericStreamPipeline<,>)); + } + ); var query = new SomeStreamingQuery(Guid.NewGuid()); diff --git a/test/Mediator.Tests/RequestInheritanceTests.cs b/test/Mediator.Tests/RequestInheritanceTests.cs index dbc2b6e..1286097 100644 --- a/test/Mediator.Tests/RequestInheritanceTests.cs +++ b/test/Mediator.Tests/RequestInheritanceTests.cs @@ -49,9 +49,9 @@ public CreateRequestWithN(Guid id, int N) : base(id) public int N { get; } } - public sealed class CreateHandler : - IRequestHandler, - IRequestHandler + public sealed class CreateHandler + : IRequestHandler, + IRequestHandler { internal static readonly ConcurrentBag Ids = new(); internal static readonly ConcurrentBag IdsForN = new(); diff --git a/test/Mediator.Tests/StreamingTests.cs b/test/Mediator.Tests/StreamingTests.cs index 7ebd522..e613dfe 100644 --- a/test/Mediator.Tests/StreamingTests.cs +++ b/test/Mediator.Tests/StreamingTests.cs @@ -6,10 +6,10 @@ public sealed class StreamingTests { public static IEnumerable TestMessages = new IStreamMessage[][] { - new IStreamMessage[] { new SomeStreamingQuery(Guid.NewGuid()) }, - new IStreamMessage[] { new SomeStreamingCommand(Guid.NewGuid()) }, - new IStreamMessage[] { new SomeStreamingQuery(Guid.NewGuid()) }, - new IStreamMessage[] { new SomeStreamingCommandStruct(Guid.NewGuid()) }, + new IStreamMessage[] { new SomeStreamingQuery(Guid.NewGuid()) }, + new IStreamMessage[] { new SomeStreamingCommand(Guid.NewGuid()) }, + new IStreamMessage[] { new SomeStreamingQuery(Guid.NewGuid()) }, + new IStreamMessage[] { new SomeStreamingCommandStruct(Guid.NewGuid()) }, }; private static Guid GetId(IStreamMessage message) => (Guid)message.GetType().GetProperty("Id")!.GetValue(message)!; diff --git a/test/Mediator.Tests/StructResponseTests.cs b/test/Mediator.Tests/StructResponseTests.cs index 3c6d6ed..4c56d57 100644 --- a/test/Mediator.Tests/StructResponseTests.cs +++ b/test/Mediator.Tests/StructResponseTests.cs @@ -5,17 +5,20 @@ public sealed class StructResponseTests public readonly struct Response { public readonly Guid Id; + public Response(Guid id) => Id = id; } public sealed record Request(Guid Id) : IRequest; + public sealed record Command(Guid Id) : ICommand; + public sealed record Query(Guid Id) : IQuery; - public sealed class Handler : - IRequestHandler, - ICommandHandler, - IQueryHandler + public sealed class Handler + : IRequestHandler, + ICommandHandler, + IQueryHandler { public ValueTask Handle(Request request, CancellationToken cancellationToken) => new ValueTask(new Response(request.Id)); diff --git a/test/Mediator.Tests/TestTypes/SomeCommand.cs b/test/Mediator.Tests/TestTypes/SomeCommand.cs index bb3274c..9834419 100644 --- a/test/Mediator.Tests/TestTypes/SomeCommand.cs +++ b/test/Mediator.Tests/TestTypes/SomeCommand.cs @@ -1,6 +1,7 @@ namespace Mediator.Tests.TestTypes; public sealed record SomeCommand(Guid Id) : ICommand; + public sealed record SomeCommandWithoutResponse(Guid Id) : ICommand; public readonly struct SomeStructCommand : ICommand diff --git a/test/Mediator.Tests/TestTypes/SomeQueryHandler.cs b/test/Mediator.Tests/TestTypes/SomeQueryHandler.cs index 4ebdf3c..7821bb0 100644 --- a/test/Mediator.Tests/TestTypes/SomeQueryHandler.cs +++ b/test/Mediator.Tests/TestTypes/SomeQueryHandler.cs @@ -2,5 +2,6 @@ namespace Mediator.Tests.TestTypes; public sealed class SomeQueryHandler : IQueryHandler { - public ValueTask Handle(SomeQuery Query, CancellationToken cancellationToken) => new ValueTask(new SomeResponse(Query.Id)); + public ValueTask Handle(SomeQuery Query, CancellationToken cancellationToken) => + new ValueTask(new SomeResponse(Query.Id)); } diff --git a/test/Mediator.Tests/TestTypes/SomeRequestHandler.cs b/test/Mediator.Tests/TestTypes/SomeRequestHandler.cs index 2fbfc48..ca2fc4a 100644 --- a/test/Mediator.Tests/TestTypes/SomeRequestHandler.cs +++ b/test/Mediator.Tests/TestTypes/SomeRequestHandler.cs @@ -4,7 +4,8 @@ namespace Mediator.Tests.TestTypes; public sealed class SomeRequestHandler : IRequestHandler { - public ValueTask Handle(SomeRequest request, CancellationToken cancellationToken) => new ValueTask(new SomeResponse(request.Id)); + public ValueTask Handle(SomeRequest request, CancellationToken cancellationToken) => + new ValueTask(new SomeResponse(request.Id)); } public sealed class SomeRequestWithoutResponseHandler : IRequestHandler @@ -26,7 +27,10 @@ public sealed class SomeStaticNestedHandler : IRequestHandler Ids = new(); - public async ValueTask Handle(SomeStaticNestedRequest request, CancellationToken cancellationToken) + public async ValueTask Handle( + SomeStaticNestedRequest request, + CancellationToken cancellationToken + ) { await Task.Yield(); Ids.Add(request.Id); diff --git a/test/Mediator.Tests/TestTypes/SomeStreamingCommand.cs b/test/Mediator.Tests/TestTypes/SomeStreamingCommand.cs index d3dff8a..a76d930 100644 --- a/test/Mediator.Tests/TestTypes/SomeStreamingCommand.cs +++ b/test/Mediator.Tests/TestTypes/SomeStreamingCommand.cs @@ -4,7 +4,10 @@ public sealed record SomeStreamingCommand(Guid Id) : IStreamCommand { - public async IAsyncEnumerable Handle(SomeStreamingCommand command, [EnumeratorCancellation] CancellationToken cancellationToken) + public async IAsyncEnumerable Handle( + SomeStreamingCommand command, + [EnumeratorCancellation] CancellationToken cancellationToken + ) { for (int i = 0; i < 3; i++) { diff --git a/test/Mediator.Tests/TestTypes/SomeStreamingCommandStruct.cs b/test/Mediator.Tests/TestTypes/SomeStreamingCommandStruct.cs index 2f966f1..b5a15eb 100644 --- a/test/Mediator.Tests/TestTypes/SomeStreamingCommandStruct.cs +++ b/test/Mediator.Tests/TestTypes/SomeStreamingCommandStruct.cs @@ -4,7 +4,10 @@ public record struct SomeStreamingCommandStruct(Guid Id) : IStreamCommand { - public async IAsyncEnumerable Handle(SomeStreamingCommandStruct command, [EnumeratorCancellation] CancellationToken cancellationToken) + public async IAsyncEnumerable Handle( + SomeStreamingCommandStruct command, + [EnumeratorCancellation] CancellationToken cancellationToken + ) { for (int i = 0; i < 3; i++) { diff --git a/test/Mediator.Tests/TestTypes/SomeStreamingQuery.cs b/test/Mediator.Tests/TestTypes/SomeStreamingQuery.cs index 2772474..704cc92 100644 --- a/test/Mediator.Tests/TestTypes/SomeStreamingQuery.cs +++ b/test/Mediator.Tests/TestTypes/SomeStreamingQuery.cs @@ -4,7 +4,10 @@ public sealed record SomeStreamingQuery(Guid Id) : IStreamQuery; public sealed class SomeStreamingQueryHandler : IStreamQueryHandler { - public async IAsyncEnumerable Handle(SomeStreamingQuery query, [EnumeratorCancellation] CancellationToken cancellationToken) + public async IAsyncEnumerable Handle( + SomeStreamingQuery query, + [EnumeratorCancellation] CancellationToken cancellationToken + ) { for (int i = 0; i < 3; i++) { diff --git a/test/Mediator.Tests/TestTypes/SomeStreamingRequest.cs b/test/Mediator.Tests/TestTypes/SomeStreamingRequest.cs index fc388c4..bfc14b1 100644 --- a/test/Mediator.Tests/TestTypes/SomeStreamingRequest.cs +++ b/test/Mediator.Tests/TestTypes/SomeStreamingRequest.cs @@ -4,7 +4,10 @@ public sealed record SomeStreamingRequest(Guid Id) : IStreamRequest { - public async IAsyncEnumerable Handle(SomeStreamingRequest request, [EnumeratorCancellation] CancellationToken cancellationToken) + public async IAsyncEnumerable Handle( + SomeStreamingRequest request, + [EnumeratorCancellation] CancellationToken cancellationToken + ) { for (int i = 0; i < 3; i++) {