diff --git a/Core.ElasticSearch/Projections/ElasticSearchProjection.cs b/Core.ElasticSearch/Projections/ElasticSearchProjection.cs index 0315bc84b..d2433d2ee 100644 --- a/Core.ElasticSearch/Projections/ElasticSearchProjection.cs +++ b/Core.ElasticSearch/Projections/ElasticSearchProjection.cs @@ -6,21 +6,15 @@ namespace Core.ElasticSearch.Projections; -public class ElasticSearchProjection : IEventHandler> +public class ElasticSearchProjection( + ElasticsearchClient elasticClient, + Func getId) + : IEventHandler> where TView : class, IProjection where TEvent : notnull { - private readonly ElasticsearchClient elasticClient; - private readonly Func getId; - - public ElasticSearchProjection( - ElasticsearchClient elasticClient, - Func getId - ) - { - this.elasticClient = elasticClient ?? throw new ArgumentNullException(nameof(elasticClient)); - this.getId = getId ?? throw new ArgumentNullException(nameof(getId)); - } + private readonly ElasticsearchClient elasticClient = elasticClient ?? throw new ArgumentNullException(nameof(elasticClient)); + private readonly Func getId = getId ?? throw new ArgumentNullException(nameof(getId)); public async Task Handle(EventEnvelope eventEnvelope, CancellationToken ct) { diff --git a/Core.ElasticSearch/Repository/ElasticSearchRepository.cs b/Core.ElasticSearch/Repository/ElasticSearchRepository.cs index da3a29c86..4cc6d8943 100644 --- a/Core.ElasticSearch/Repository/ElasticSearchRepository.cs +++ b/Core.ElasticSearch/Repository/ElasticSearchRepository.cs @@ -13,16 +13,10 @@ public interface IElasticSearchRepository where T : class, IAggregate Task Delete(T aggregate, CancellationToken cancellationToken); } -public class ElasticSearchRepository: IElasticSearchRepository where T : class, IAggregate +public class ElasticSearchRepository(ElasticsearchClient elasticClient): IElasticSearchRepository + where T : class, IAggregate { - private readonly ElasticsearchClient elasticClient; - - public ElasticSearchRepository( - ElasticsearchClient elasticClient - ) - { - this.elasticClient = elasticClient ?? throw new ArgumentNullException(nameof(elasticClient)); - } + private readonly ElasticsearchClient elasticClient = elasticClient ?? throw new ArgumentNullException(nameof(elasticClient)); public async Task Find(Guid id, CancellationToken cancellationToken) { diff --git a/Core.EventStoreDB.Tests/Commands/EventStoreDBAsyncCommandBusTests.cs b/Core.EventStoreDB.Tests/Commands/EventStoreDBAsyncCommandBusTests.cs index 4dd3b0493..0ab2ac23c 100644 --- a/Core.EventStoreDB.Tests/Commands/EventStoreDBAsyncCommandBusTests.cs +++ b/Core.EventStoreDB.Tests/Commands/EventStoreDBAsyncCommandBusTests.cs @@ -92,13 +92,8 @@ public async Task CommandIsStoredInEventStoreDBAndForwardedToCommandHandler() public record AddUser(Guid UserId, string? Sth = default); -internal class AddUserCommandHandler: ICommandHandler +internal class AddUserCommandHandler(List userIds): ICommandHandler { - private readonly List userIds; - - public AddUserCommandHandler(List userIds) => - this.userIds = userIds; - public Task Handle(AddUser command, CancellationToken ct) { userIds.Add(command.UserId); diff --git a/Core.EventStoreDB/Commands/EventStoreDBAsyncCommandBus.cs b/Core.EventStoreDB/Commands/EventStoreDBAsyncCommandBus.cs index c4613618c..e3b8ab6ae 100644 --- a/Core.EventStoreDB/Commands/EventStoreDBAsyncCommandBus.cs +++ b/Core.EventStoreDB/Commands/EventStoreDBAsyncCommandBus.cs @@ -9,15 +9,10 @@ namespace Core.EventStoreDB.Commands; /// Note: This is an example of the outbox pattern for Command Bus using EventStoreDB /// For production use mature tooling like Wolverine, MassTransit or NServiceBus /// -public class EventStoreDBAsyncCommandBus : IAsyncCommandBus +public class EventStoreDBAsyncCommandBus(EventStoreClient eventStoreClient): IAsyncCommandBus { public static readonly string CommandsStreamId = "commands-external"; - private readonly EventStoreClient eventStoreClient; - - public EventStoreDBAsyncCommandBus(EventStoreClient eventStoreClient) => - this.eventStoreClient = eventStoreClient; - public Task Schedule(TCommand command, CancellationToken ct = default) where TCommand: notnull { return eventStoreClient.Append(CommandsStreamId, command, ct); diff --git a/Core.EventStoreDB/Repository/EventStoreDBRepository.cs b/Core.EventStoreDB/Repository/EventStoreDBRepository.cs index d967f76a2..83075b070 100644 --- a/Core.EventStoreDB/Repository/EventStoreDBRepository.cs +++ b/Core.EventStoreDB/Repository/EventStoreDBRepository.cs @@ -16,19 +16,13 @@ public interface IEventStoreDBRepository where T : class, IAggregate Task Delete(T aggregate, ulong? expectedRevision = null, CancellationToken ct = default); } -public class EventStoreDBRepository: IEventStoreDBRepository where T : class, IAggregate +public class EventStoreDBRepository( + EventStoreClient eventStore, + IActivityScope activityScope) + : IEventStoreDBRepository + where T : class, IAggregate { - private readonly EventStoreClient eventStore; - private readonly IActivityScope activityScope; - - public EventStoreDBRepository( - EventStoreClient eventStore, - IActivityScope activityScope - ) - { - this.eventStore = eventStore; - this.activityScope = activityScope; - } + private readonly IActivityScope activityScope = activityScope; public Task Find(Guid id, CancellationToken cancellationToken) => eventStore.AggregateStream( diff --git a/Core.EventStoreDB/Repository/EventStoreDBRepositoryWithETagDecorator.cs b/Core.EventStoreDB/Repository/EventStoreDBRepositoryWithETagDecorator.cs index 60f742e38..708e00947 100644 --- a/Core.EventStoreDB/Repository/EventStoreDBRepositoryWithETagDecorator.cs +++ b/Core.EventStoreDB/Repository/EventStoreDBRepositoryWithETagDecorator.cs @@ -3,24 +3,13 @@ namespace Core.EventStoreDB.Repository; -public class EventStoreDBRepositoryWithETagDecorator: IEventStoreDBRepository +public class EventStoreDBRepositoryWithETagDecorator( + IEventStoreDBRepository inner, + IExpectedResourceVersionProvider expectedResourceVersionProvider, + INextResourceVersionProvider nextResourceVersionProvider) + : IEventStoreDBRepository where T : class, IAggregate { - private readonly IEventStoreDBRepository inner; - private readonly IExpectedResourceVersionProvider expectedResourceVersionProvider; - private readonly INextResourceVersionProvider nextResourceVersionProvider; - - public EventStoreDBRepositoryWithETagDecorator( - IEventStoreDBRepository inner, - IExpectedResourceVersionProvider expectedResourceVersionProvider, - INextResourceVersionProvider nextResourceVersionProvider - ) - { - this.inner = inner; - this.expectedResourceVersionProvider = expectedResourceVersionProvider; - this.nextResourceVersionProvider = nextResourceVersionProvider; - } - public Task Find(Guid id, CancellationToken cancellationToken) => inner.Find(id, cancellationToken); diff --git a/Core.EventStoreDB/Repository/EventStoreDBRepositoryWithTelemetryDecorator.cs b/Core.EventStoreDB/Repository/EventStoreDBRepositoryWithTelemetryDecorator.cs index 45e7d9b89..9950ae018 100644 --- a/Core.EventStoreDB/Repository/EventStoreDBRepositoryWithTelemetryDecorator.cs +++ b/Core.EventStoreDB/Repository/EventStoreDBRepositoryWithTelemetryDecorator.cs @@ -4,21 +4,12 @@ namespace Core.EventStoreDB.Repository; -public class EventStoreDBRepositoryWithTelemetryDecorator: IEventStoreDBRepository +public class EventStoreDBRepositoryWithTelemetryDecorator( + IEventStoreDBRepository inner, + IActivityScope activityScope) + : IEventStoreDBRepository where T : class, IAggregate { - private readonly IEventStoreDBRepository inner; - private readonly IActivityScope activityScope; - - public EventStoreDBRepositoryWithTelemetryDecorator( - IEventStoreDBRepository inner, - IActivityScope activityScope - ) - { - this.inner = inner; - this.activityScope = activityScope; - } - public Task Find(Guid id, CancellationToken cancellationToken) => inner.Find(id, cancellationToken); diff --git a/Core.EventStoreDB/Subscriptions/EventStoreDBSubscriptionCheckpointRepository.cs b/Core.EventStoreDB/Subscriptions/EventStoreDBSubscriptionCheckpointRepository.cs index dcc516470..ae75c8e46 100644 --- a/Core.EventStoreDB/Subscriptions/EventStoreDBSubscriptionCheckpointRepository.cs +++ b/Core.EventStoreDB/Subscriptions/EventStoreDBSubscriptionCheckpointRepository.cs @@ -5,15 +5,10 @@ namespace Core.EventStoreDB.Subscriptions; public record CheckpointStored(string SubscriptionId, ulong? Position, DateTime CheckpointedAt); -public class EventStoreDBSubscriptionCheckpointRepository: ISubscriptionCheckpointRepository +public class EventStoreDBSubscriptionCheckpointRepository(EventStoreClient eventStoreClient) + : ISubscriptionCheckpointRepository { - private readonly EventStoreClient eventStoreClient; - - public EventStoreDBSubscriptionCheckpointRepository( - EventStoreClient eventStoreClient) - { - this.eventStoreClient = eventStoreClient ?? throw new ArgumentNullException(nameof(eventStoreClient)); - } + private readonly EventStoreClient eventStoreClient = eventStoreClient ?? throw new ArgumentNullException(nameof(eventStoreClient)); public async ValueTask Load(string subscriptionId, CancellationToken ct) { diff --git a/Core.Marten/Commands/MartenAsyncCommandBus.cs b/Core.Marten/Commands/MartenAsyncCommandBus.cs index 94be36ad2..7a81bd6ae 100644 --- a/Core.Marten/Commands/MartenAsyncCommandBus.cs +++ b/Core.Marten/Commands/MartenAsyncCommandBus.cs @@ -8,15 +8,10 @@ namespace Core.Marten.Commands; /// Note: This is an example of the outbox pattern for Command Bus using Marten /// For production use mature tooling like Wolverine, MassTransit or NServiceBus /// -public class MartenAsyncCommandBus : IAsyncCommandBus +public class MartenAsyncCommandBus(IDocumentSession documentSession): IAsyncCommandBus { public static readonly Guid CommandsStreamId = new("11111111-1111-1111-1111-111111111111"); - private readonly IDocumentSession documentSession; - - public MartenAsyncCommandBus(IDocumentSession documentSession) => - this.documentSession = documentSession; - public Task Schedule(TCommand command, CancellationToken ct = default) where TCommand: notnull { documentSession.Events.Append(CommandsStreamId, command); diff --git a/Core.Marten/ExternalProjections/MartenExternalProjection.cs b/Core.Marten/ExternalProjections/MartenExternalProjection.cs index 1c91068e3..61e4556b5 100644 --- a/Core.Marten/ExternalProjections/MartenExternalProjection.cs +++ b/Core.Marten/ExternalProjections/MartenExternalProjection.cs @@ -5,22 +5,12 @@ namespace Core.Marten.ExternalProjections; -public class MartenExternalProjection: IEventHandler> +public class MartenExternalProjection( + IDocumentSession session, + Func getId): IEventHandler> where TView : IVersionedProjection where TEvent : notnull { - private readonly IDocumentSession session; - private readonly Func getId; - - public MartenExternalProjection( - IDocumentSession session, - Func getId - ) - { - this.session = session; - this.getId = getId; - } - public async Task Handle(EventEnvelope eventEnvelope, CancellationToken ct) { var (@event, eventMetadata) = eventEnvelope; diff --git a/Core.Marten/Ids/MartenIdGenerator.cs b/Core.Marten/Ids/MartenIdGenerator.cs index 0650ff43b..61e47eb2d 100644 --- a/Core.Marten/Ids/MartenIdGenerator.cs +++ b/Core.Marten/Ids/MartenIdGenerator.cs @@ -4,14 +4,9 @@ namespace Core.Marten.Ids; -public class MartenIdGenerator : IIdGenerator +public class MartenIdGenerator(IDocumentSession documentSession): IIdGenerator { - private readonly IDocumentSession documentSession; - - public MartenIdGenerator(IDocumentSession documentSession) - { - this.documentSession = documentSession ?? throw new ArgumentNullException(nameof(documentSession)); - } + private readonly IDocumentSession documentSession = documentSession ?? throw new ArgumentNullException(nameof(documentSession)); public Guid New() => CombGuidIdGeneration.NewGuid(); } diff --git a/Core.Marten/OpenTelemetry/MartenRepositoryWithTelemetryDecorator.cs b/Core.Marten/OpenTelemetry/MartenRepositoryWithTelemetryDecorator.cs index 94de29c4e..9acd10f41 100644 --- a/Core.Marten/OpenTelemetry/MartenRepositoryWithTelemetryDecorator.cs +++ b/Core.Marten/OpenTelemetry/MartenRepositoryWithTelemetryDecorator.cs @@ -6,27 +6,14 @@ namespace Core.Marten.Repository; -public class MartenRepositoryWithTracingDecorator: IMartenRepository +public class MartenRepositoryWithTracingDecorator( + IMartenRepository inner, + IDocumentSession documentSession, + IActivityScope activityScope, + ILogger> logger) + : IMartenRepository where T : class, IAggregate { - private readonly IMartenRepository inner; - private readonly IDocumentSession documentSession; - private readonly IActivityScope activityScope; - private readonly ILogger> logger; - - public MartenRepositoryWithTracingDecorator( - IMartenRepository inner, - IDocumentSession documentSession, - IActivityScope activityScope, - ILogger> logger - ) - { - this.inner = inner; - this.activityScope = activityScope; - this.logger = logger; - this.documentSession = documentSession; - } - public Task Find(Guid id, CancellationToken cancellationToken) => inner.Find(id, cancellationToken); diff --git a/Core.Marten/Repository/MartenRepository.cs b/Core.Marten/Repository/MartenRepository.cs index 09da914b7..4c4db14aa 100644 --- a/Core.Marten/Repository/MartenRepository.cs +++ b/Core.Marten/Repository/MartenRepository.cs @@ -14,13 +14,9 @@ public interface IMartenRepository where T : class, IAggregate Task Delete(T aggregate, long? expectedVersion = null, CancellationToken cancellationToken = default); } -public class MartenRepository: IMartenRepository where T : class, IAggregate +public class MartenRepository(IDocumentSession documentSession): IMartenRepository + where T : class, IAggregate { - private readonly IDocumentSession documentSession; - - public MartenRepository(IDocumentSession documentSession) => - this.documentSession = documentSession; - public Task Find(Guid id, CancellationToken ct) => documentSession.Events.AggregateStreamAsync(id, token: ct); diff --git a/Core.Marten/Repository/MartenRepositoryWithETagDecorator.cs b/Core.Marten/Repository/MartenRepositoryWithETagDecorator.cs index 0b56991b1..45efd9323 100644 --- a/Core.Marten/Repository/MartenRepositoryWithETagDecorator.cs +++ b/Core.Marten/Repository/MartenRepositoryWithETagDecorator.cs @@ -3,24 +3,13 @@ namespace Core.Marten.Repository; -public class MartenRepositoryWithETagDecorator: IMartenRepository +public class MartenRepositoryWithETagDecorator( + IMartenRepository inner, + IExpectedResourceVersionProvider expectedResourceVersionProvider, + INextResourceVersionProvider nextResourceVersionProvider) + : IMartenRepository where T : class, IAggregate { - private readonly IMartenRepository inner; - private readonly IExpectedResourceVersionProvider expectedResourceVersionProvider; - private readonly INextResourceVersionProvider nextResourceVersionProvider; - - public MartenRepositoryWithETagDecorator( - IMartenRepository inner, - IExpectedResourceVersionProvider expectedResourceVersionProvider, - INextResourceVersionProvider nextResourceVersionProvider - ) - { - this.inner = inner; - this.expectedResourceVersionProvider = expectedResourceVersionProvider; - this.nextResourceVersionProvider = nextResourceVersionProvider; - } - public Task Find(Guid id, CancellationToken cancellationToken) => inner.Find(id, cancellationToken); diff --git a/Core.Marten/Serialization/NonDefaultConstructorMartenJsonNetContractResolver.cs b/Core.Marten/Serialization/NonDefaultConstructorMartenJsonNetContractResolver.cs index 01dfa05bc..94bd85387 100644 --- a/Core.Marten/Serialization/NonDefaultConstructorMartenJsonNetContractResolver.cs +++ b/Core.Marten/Serialization/NonDefaultConstructorMartenJsonNetContractResolver.cs @@ -5,17 +5,12 @@ namespace Core.Marten.Serialization; -public class NonDefaultConstructorMartenJsonNetContractResolver: JsonNetContractResolver +public class NonDefaultConstructorMartenJsonNetContractResolver( + Casing casing, + CollectionStorage collectionStorage, + NonPublicMembersStorage nonPublicMembersStorage = NonPublicMembersStorage.Default) + : JsonNetContractResolver(casing, collectionStorage, nonPublicMembersStorage) { - public NonDefaultConstructorMartenJsonNetContractResolver( - Casing casing, - CollectionStorage collectionStorage, - NonPublicMembersStorage nonPublicMembersStorage = NonPublicMembersStorage.Default): - base(casing, collectionStorage, nonPublicMembersStorage) - { - - } - protected override JsonObjectContract CreateObjectContract(Type objectType) { return JsonObjectContractProvider.UsingNonDefaultConstructor( diff --git a/Core.Testing/EventListener.cs b/Core.Testing/EventListener.cs index 19020344f..9e22bcf68 100644 --- a/Core.Testing/EventListener.cs +++ b/Core.Testing/EventListener.cs @@ -32,17 +32,8 @@ await foreach (var item in events.Reader.ReadAllAsync(ct).ConfigureAwait(false)) events.Reader.ReadAllAsync(ct); } -public class EventCatcher: IEventBus +public class EventCatcher(EventListener listener, IEventBus eventBus): IEventBus { - private readonly EventListener listener; - private readonly IEventBus eventBus; - - public EventCatcher(EventListener listener, IEventBus eventBus) - { - this.listener = listener; - this.eventBus = eventBus; - } - public async Task Publish(IEventEnvelope @event, CancellationToken ct) { await eventBus.Publish(@event, ct).ConfigureAwait(false); diff --git a/Core.WebApi/OptimisticConcurrency/OptimisticConcurrencyMiddleware.cs b/Core.WebApi/OptimisticConcurrency/OptimisticConcurrencyMiddleware.cs index f8029c41d..fda455af4 100644 --- a/Core.WebApi/OptimisticConcurrency/OptimisticConcurrencyMiddleware.cs +++ b/Core.WebApi/OptimisticConcurrency/OptimisticConcurrencyMiddleware.cs @@ -8,22 +8,13 @@ namespace Core.WebApi.OptimisticConcurrency; -public class OptimisticConcurrencyMiddleware +public class OptimisticConcurrencyMiddleware(RequestDelegate next) { - private readonly RequestDelegate next; - private readonly string[] SupportedMethods = [ HttpMethod.Post.Method, HttpMethod.Put.Method, HttpMethod.Delete.Method ]; - public OptimisticConcurrencyMiddleware( - RequestDelegate next - ) - { - this.next = next; - } - public async Task Invoke( HttpContext context, IExpectedResourceVersionProvider expectedResourceVersionProvider, diff --git a/Core/BackgroundWorkers/BackgroundWorker.cs b/Core/BackgroundWorkers/BackgroundWorker.cs index 5cb997112..e0959b11e 100644 --- a/Core/BackgroundWorkers/BackgroundWorker.cs +++ b/Core/BackgroundWorkers/BackgroundWorker.cs @@ -3,20 +3,11 @@ namespace Core.BackgroundWorkers; -public class BackgroundWorker: BackgroundService +public class BackgroundWorker( + ILogger logger, + Func perform) + : BackgroundService { - private readonly ILogger logger; - private readonly Func perform; - - public BackgroundWorker( - ILogger logger, - Func perform - ) - { - this.logger = logger; - this.perform = perform; - } - protected override Task ExecuteAsync(CancellationToken stoppingToken) => Task.Run(async () => { diff --git a/Core/Commands/CommandForwarder.cs b/Core/Commands/CommandForwarder.cs index 7c871523d..75a004c03 100644 --- a/Core/Commands/CommandForwarder.cs +++ b/Core/Commands/CommandForwarder.cs @@ -7,15 +7,9 @@ namespace Core.Commands; /// Note: This is an example of the outbox pattern for Command Bus using EventStoreDB /// For production use mature tooling like Wolverine, MassTransit or NServiceBus /// -public class CommandForwarder: IEventHandler where T : notnull +public class CommandForwarder(ICommandBus commandBus): IEventHandler + where T : notnull { - private readonly ICommandBus commandBus; - - public CommandForwarder(ICommandBus commandBus) - { - this.commandBus = commandBus; - } - public async Task Handle(T command, CancellationToken ct) { await commandBus.TrySend(command, ct).ConfigureAwait(false); diff --git a/Core/Events/EventBus.cs b/Core/Events/EventBus.cs index 8f7d5b491..1699981e5 100644 --- a/Core/Events/EventBus.cs +++ b/Core/Events/EventBus.cs @@ -12,24 +12,14 @@ public interface IEventBus Task Publish(IEventEnvelope @event, CancellationToken ct); } -public class EventBus: IEventBus +public class EventBus( + IServiceProvider serviceProvider, + IActivityScope activityScope, + AsyncPolicy retryPolicy) + : IEventBus { - private readonly IServiceProvider serviceProvider; - private readonly IActivityScope activityScope; - private readonly AsyncPolicy retryPolicy; private static readonly ConcurrentDictionary PublishMethods = new(); - public EventBus( - IServiceProvider serviceProvider, - IActivityScope activityScope, - AsyncPolicy retryPolicy - ) - { - this.serviceProvider = serviceProvider; - this.activityScope = activityScope; - this.retryPolicy = retryPolicy; - } - private async Task Publish(EventEnvelope eventEnvelope, CancellationToken ct) where TEvent : notnull { diff --git a/Core/Events/External/IExternaEventProducer.cs b/Core/Events/External/IExternaEventProducer.cs index b155496fa..89b41e3bc 100644 --- a/Core/Events/External/IExternaEventProducer.cs +++ b/Core/Events/External/IExternaEventProducer.cs @@ -6,20 +6,11 @@ public interface IExternalEventProducer } -public class EventBusDecoratorWithExternalProducer: IEventBus +public class EventBusDecoratorWithExternalProducer( + IEventBus eventBus, + IExternalEventProducer externalEventProducer) + : IEventBus { - private readonly IEventBus eventBus; - private readonly IExternalEventProducer externalEventProducer; - - public EventBusDecoratorWithExternalProducer( - IEventBus eventBus, - IExternalEventProducer externalEventProducer - ) - { - this.eventBus = eventBus; - this.externalEventProducer = externalEventProducer; - } - public async Task Publish(IEventEnvelope eventEnvelope, CancellationToken ct) { await eventBus.Publish(eventEnvelope, ct).ConfigureAwait(false); diff --git a/Core/Events/IEventHandler.cs b/Core/Events/IEventHandler.cs index 28891cc93..46ad623c2 100644 --- a/Core/Events/IEventHandler.cs +++ b/Core/Events/IEventHandler.cs @@ -5,13 +5,8 @@ public interface IEventHandler Task Handle(TEvent @event, CancellationToken ct); } -public class EventHandler : IEventHandler +public class EventHandler(Func handler): IEventHandler { - private readonly Func handler; - - public EventHandler(Func handler) => - this.handler = handler; - public Task Handle(TEvent @event, CancellationToken ct) => handler(@event, ct); } diff --git a/Core/Queries/QueryBus.cs b/Core/Queries/QueryBus.cs index 72edd7c60..1107b96a9 100644 --- a/Core/Queries/QueryBus.cs +++ b/Core/Queries/QueryBus.cs @@ -5,23 +5,12 @@ namespace Core.Queries; -public class QueryBus: IQueryBus +public class QueryBus( + IServiceProvider serviceProvider, + IActivityScope activityScope, + AsyncPolicy retryPolicy) + : IQueryBus { - private readonly IServiceProvider serviceProvider; - private readonly AsyncPolicy retryPolicy; - private readonly IActivityScope activityScope; - - public QueryBus( - IServiceProvider serviceProvider, - IActivityScope activityScope, - AsyncPolicy retryPolicy - ) - { - this.serviceProvider = serviceProvider; - this.retryPolicy = retryPolicy; - this.activityScope = activityScope; - } - public Task Query(TQuery query, CancellationToken ct = default) where TQuery : notnull { diff --git a/Core/Responses/PagedListResponse.cs b/Core/Responses/PagedListResponse.cs index 0ee54e972..767f58d55 100644 --- a/Core/Responses/PagedListResponse.cs +++ b/Core/Responses/PagedListResponse.cs @@ -1,17 +1,10 @@ namespace Core.Responses; -public class PagedListResponse +public class PagedListResponse(IEnumerable items, long totalItemCount, bool hasNextPage) { - public IReadOnlyList Items { get; } + public IReadOnlyList Items { get; } = items.ToList(); - public long TotalItemCount { get; } + public long TotalItemCount { get; } = totalItemCount; - public bool HasNextPage { get; } - - public PagedListResponse(IEnumerable items, long totalItemCount, bool hasNextPage) - { - Items = items.ToList(); - TotalItemCount = totalItemCount; - HasNextPage = hasNextPage; - } -} \ No newline at end of file + public bool HasNextPage { get; } = hasNextPage; +} diff --git a/Core/Threading/NoSynchronizationContextScope.cs b/Core/Threading/NoSynchronizationContextScope.cs index 585c402fc..fe1a7c984 100644 --- a/Core/Threading/NoSynchronizationContextScope.cs +++ b/Core/Threading/NoSynchronizationContextScope.cs @@ -9,16 +9,9 @@ public static Disposable Enter() return new Disposable(context); } - public struct Disposable: IDisposable + public struct Disposable(SynchronizationContext? synchronizationContext): IDisposable { - private readonly SynchronizationContext? synchronizationContext; - - public Disposable(SynchronizationContext? synchronizationContext) - { - this.synchronizationContext = synchronizationContext; - } - public void Dispose() => SynchronizationContext.SetSynchronizationContext(synchronizationContext); } -} \ No newline at end of file +} diff --git a/Marten.Integration.Tests/Commands/MartenAsyncCommandBusTests.cs b/Marten.Integration.Tests/Commands/MartenAsyncCommandBusTests.cs index 7002b98ee..536e25964 100644 --- a/Marten.Integration.Tests/Commands/MartenAsyncCommandBusTests.cs +++ b/Marten.Integration.Tests/Commands/MartenAsyncCommandBusTests.cs @@ -94,13 +94,8 @@ public override async Task InitializeAsync() public record AddUser(Guid UserId, string? Sth = default); -internal class AddUserCommandHandler: ICommandHandler +internal class AddUserCommandHandler(List userIds): ICommandHandler { - private readonly List userIds; - - public AddUserCommandHandler(List userIds) => - this.userIds = userIds; - public Task Handle(AddUser command, CancellationToken ct) { userIds.Add(command.UserId); diff --git a/Marten.Integration.Tests/CompositeIds/CompositeIdsTests.cs b/Marten.Integration.Tests/CompositeIds/CompositeIdsTests.cs index b6305a9c8..c39ffc2eb 100644 --- a/Marten.Integration.Tests/CompositeIds/CompositeIdsTests.cs +++ b/Marten.Integration.Tests/CompositeIds/CompositeIdsTests.cs @@ -8,14 +8,10 @@ namespace Marten.Integration.Tests.CompositeIds; -public class StronglyTypedValue: IEquatable> where T : IComparable +public class StronglyTypedValue(T value): IEquatable> + where T : IComparable { - public T Value { get; } - - public StronglyTypedValue(T value) - { - Value = value; - } + public T Value { get; } = value; public bool Equals(StronglyTypedValue? other) { @@ -48,26 +44,11 @@ public override int GetHashCode() } } -public class ReservationId: StronglyTypedValue -{ - public ReservationId(Guid value): base(value) - { - } -} +public class ReservationId(Guid value): StronglyTypedValue(value); -public class CustomerId: StronglyTypedValue -{ - public CustomerId(Guid value): base(value) - { - } -} +public class CustomerId(Guid value): StronglyTypedValue(value); -public class SeatId: StronglyTypedValue -{ - public SeatId(Guid value): base(value) - { - } -} +public class SeatId(Guid value): StronglyTypedValue(value); public class ReservationNumber: StronglyTypedValue { @@ -242,7 +223,7 @@ public void Apply(ReservationCancelled @event) } } -public class CompositeIdsTests: MartenTest +public class CompositeIdsTests(MartenFixture fixture): MartenTest(fixture.PostgreSqlContainer) { private const string FirstTenant = "Tenant1"; private const string SecondTenant = "Tenant2"; @@ -301,8 +282,4 @@ public void GivenAggregateWithCompositeId_WhenAppendedEvent_LiveAndInlineAggrega issuesListFromInlineAggregationFromLinq!.AggregateId.Should().Be(reservationId.Value); issuesListFromInlineAggregationFromLinqWithAggregateId!.AggregateId.Should().Be(reservationId.Value); } - - public CompositeIdsTests(MartenFixture fixture): base(fixture.PostgreSqlContainer) - { - } } diff --git a/Marten.Integration.Tests/EventStore/Aggregate/EventsAggregation.cs b/Marten.Integration.Tests/EventStore/Aggregate/EventsAggregation.cs index 27b542b7e..6edc73e7d 100644 --- a/Marten.Integration.Tests/EventStore/Aggregate/EventsAggregation.cs +++ b/Marten.Integration.Tests/EventStore/Aggregate/EventsAggregation.cs @@ -4,7 +4,7 @@ namespace Marten.Integration.Tests.EventStore.Aggregate; -public class EventsAggregation: MartenTest +public class EventsAggregation(MartenFixture fixture): MartenTest(fixture.PostgreSqlContainer) { public record IssueCreated( Guid IssueId, @@ -100,9 +100,4 @@ public void GivenStreamOfEvents_WhenAggregateStreamIsCalled_ThenChangesAreApplie .Should() .BeEquivalentTo("Description2", "Description3"); } - - public EventsAggregation(MartenFixture fixture): base(fixture.PostgreSqlContainer) - { - - } } diff --git a/Marten.Integration.Tests/EventStore/Aggregate/InlineAggregationStorage.cs b/Marten.Integration.Tests/EventStore/Aggregate/InlineAggregationStorage.cs index b77eea9b1..7dce68527 100644 --- a/Marten.Integration.Tests/EventStore/Aggregate/InlineAggregationStorage.cs +++ b/Marten.Integration.Tests/EventStore/Aggregate/InlineAggregationStorage.cs @@ -5,7 +5,7 @@ namespace Marten.Integration.Tests.EventStore.Aggregate; -public class InlineAggregationStorage: MartenTest +public class InlineAggregationStorage(MartenFixture fixture): MartenTest(fixture.PostgreSqlContainer) { public record IssueCreated( Guid IssueId, @@ -82,6 +82,4 @@ public void GivenEvents_WhenInlineTransformationIsApplied_ThenReturnsSameNumberO issuesListFromLiveAggregation.Issues.Count.Should().Be(2); issuesListFromLiveAggregation.Issues.Count.Should().Be(issuesListFromInlineAggregation.Issues.Count); } - - public InlineAggregationStorage(MartenFixture fixture): base(fixture.PostgreSqlContainer) { } } diff --git a/Marten.Integration.Tests/EventStore/Aggregate/OutOfOrder/OutOfOrderProjectionsTest.cs b/Marten.Integration.Tests/EventStore/Aggregate/OutOfOrder/OutOfOrderProjectionsTest.cs index a89f98cc3..ce10ce5d5 100644 --- a/Marten.Integration.Tests/EventStore/Aggregate/OutOfOrder/OutOfOrderProjectionsTest.cs +++ b/Marten.Integration.Tests/EventStore/Aggregate/OutOfOrder/OutOfOrderProjectionsTest.cs @@ -6,7 +6,7 @@ namespace Marten.Integration.Tests.EventStore.Aggregate.OutOfOrder; -public class OutOfOrderProjectionsTest: MartenTest +public class OutOfOrderProjectionsTest(MartenFixture fixture): MartenTest(fixture.PostgreSqlContainer) { public record IssueCreated( Guid IssueId, @@ -94,6 +94,4 @@ public void GivenOutOfOrderEvents_WhenPublishedWithSetVersion_ThenLiveAggregatio issuesListFromLiveAggregation!.Issues.Count.Should().Be(2); issuesListFromLiveAggregation!.Issues.Count.Should().Be(issuesListFromInlineAggregation!.Issues.Count); } - - public OutOfOrderProjectionsTest(MartenFixture fixture) : base(fixture.PostgreSqlContainer){} } diff --git a/Marten.Integration.Tests/EventStore/Aggregate/Reaggregation.cs b/Marten.Integration.Tests/EventStore/Aggregate/Reaggregation.cs index 39886dd9f..d3221de9f 100644 --- a/Marten.Integration.Tests/EventStore/Aggregate/Reaggregation.cs +++ b/Marten.Integration.Tests/EventStore/Aggregate/Reaggregation.cs @@ -57,12 +57,8 @@ public void Apply(IssueUpdated @event) } } - public class Reaggregation: MartenTest + public class Reaggregation(MartenFixture fixture): MartenTest(fixture.PostgreSqlContainer, false) { - public Reaggregation(MartenFixture fixture): base(fixture.PostgreSqlContainer, false) - { - } - public IDocumentSession CreateSessionWithInlineAggregationFor() where TIssue : class, new() { return base.CreateSession(options => diff --git a/Marten.Integration.Tests/EventStore/Projections/AggregationProjectionsTest.cs b/Marten.Integration.Tests/EventStore/Projections/AggregationProjectionsTest.cs index 18171583d..7ad5d00bd 100644 --- a/Marten.Integration.Tests/EventStore/Projections/AggregationProjectionsTest.cs +++ b/Marten.Integration.Tests/EventStore/Projections/AggregationProjectionsTest.cs @@ -7,7 +7,7 @@ namespace Marten.Integration.Tests.EventStore.Projections; -public class AggregationProjectionsTest: MartenTest +public class AggregationProjectionsTest(MartenFixture fixture): MartenTest(fixture.PostgreSqlContainer) { public record IssueCreated( Guid IssueId, @@ -125,6 +125,4 @@ public void GivenEvents_WhenInlineTransformationIsApplied_ThenReturnsSameNumberO issuesListFromInlineAggregation!.Issues.Count.Should().Be(2); projection!.Descriptions.Count.Should().Be(2); } - - public AggregationProjectionsTest(MartenFixture fixture): base(fixture.PostgreSqlContainer) { } } diff --git a/Marten.Integration.Tests/EventStore/Stream/StreamLoading.cs b/Marten.Integration.Tests/EventStore/Stream/StreamLoading.cs index f1ae906c9..1946d663b 100644 --- a/Marten.Integration.Tests/EventStore/Stream/StreamLoading.cs +++ b/Marten.Integration.Tests/EventStore/Stream/StreamLoading.cs @@ -4,7 +4,7 @@ namespace Marten.Integration.Tests.EventStore.Stream; -public class StreamLoading: MartenTest +public class StreamLoading(MartenFixture fixture): MartenTest(fixture.PostgreSqlContainer) { public record IssueCreated( Guid IssueId, @@ -97,6 +97,4 @@ public async Task lastUpdatedEvent.IssueId.Should().Be(streamId); lastUpdatedEvent.Description.Should().Be("The Last One"); } - - public StreamLoading(MartenFixture fixture): base(fixture.PostgreSqlContainer) { } } diff --git a/Marten.Integration.Tests/EventStore/Stream/StreamLoadingFromExactState.cs b/Marten.Integration.Tests/EventStore/Stream/StreamLoadingFromExactState.cs index 42ff8a3bd..be214bb83 100644 --- a/Marten.Integration.Tests/EventStore/Stream/StreamLoadingFromExactState.cs +++ b/Marten.Integration.Tests/EventStore/Stream/StreamLoadingFromExactState.cs @@ -4,7 +4,7 @@ namespace Marten.Integration.Tests.EventStore.Stream; -public class StreamLoadingFromExactState: MartenTest +public class StreamLoadingFromExactState(MartenFixture fixture): MartenTest(fixture.PostgreSqlContainer) { public record IssueCreated( Guid IssueId, @@ -95,6 +95,4 @@ public void GivenSetOfEvents_WithFetchEventsFromDifferentVersionNumber_ThenPrope events = EventStore.FetchStream(streamId, 100); events.Count.Should().Be(4); } - - public StreamLoadingFromExactState(MartenFixture fixture): base(fixture.PostgreSqlContainer) { } } diff --git a/Marten.Integration.Tests/EventStore/Stream/StreamStarting.cs b/Marten.Integration.Tests/EventStore/Stream/StreamStarting.cs index 39b16e89a..e4ef89778 100644 --- a/Marten.Integration.Tests/EventStore/Stream/StreamStarting.cs +++ b/Marten.Integration.Tests/EventStore/Stream/StreamStarting.cs @@ -20,7 +20,7 @@ public record Issue( string Description ); -public class StreamStarting: MartenTest +public class StreamStarting(MartenFixture fixture): MartenTest(fixture.PostgreSqlContainer) { [Fact(Skip = "Skipped because of https://github.com/JasperFx/marten/issues/1648")] public void GivenNoEvents_WhenStreamIsStarting_ThenEventsAreSavedWithoutError() @@ -93,6 +93,4 @@ public void GivenMoreThenOneEvent_WhenStreamIsStarting_ThenEventsAreSavedWithout Session.SaveChanges(); } - - public StreamStarting(MartenFixture fixture): base(fixture.PostgreSqlContainer) { } } diff --git a/Marten.Integration.Tests/EventStore/UniqueConstraint/UniqueContstraintTests.cs b/Marten.Integration.Tests/EventStore/UniqueConstraint/UniqueContstraintTests.cs index 86820ccb7..78ae86406 100644 --- a/Marten.Integration.Tests/EventStore/UniqueConstraint/UniqueContstraintTests.cs +++ b/Marten.Integration.Tests/EventStore/UniqueConstraint/UniqueContstraintTests.cs @@ -8,7 +8,7 @@ namespace Marten.Integration.Tests.EventStore.UniqueConstraint; -public class UniqueContstraintTests: MartenTest +public class UniqueContstraintTests(MartenFixture fixture): MartenTest(fixture.PostgreSqlContainer) { public record UserCreated( Guid UserId, @@ -95,6 +95,4 @@ public async Task GivenEvents_WhenInlineTransformationIsApplied_ThenReturnsSameN EventStore.StartStream(new UserCreated(Guid.NewGuid(), "yet.another@email.com")); await Session.SaveChangesAsync(); } - - public UniqueContstraintTests(MartenFixture fixture): base(fixture.PostgreSqlContainer) { } } diff --git a/Marten.Integration.Tests/General/StoreInitializationTests.cs b/Marten.Integration.Tests/General/StoreInitializationTests.cs index 95a13bbcd..f4d9a2f70 100644 --- a/Marten.Integration.Tests/General/StoreInitializationTests.cs +++ b/Marten.Integration.Tests/General/StoreInitializationTests.cs @@ -6,7 +6,7 @@ namespace Marten.Integration.Tests.General; -public class StoreInitializationTests: MartenTest +public class StoreInitializationTests(MartenFixture fixture): MartenTest(fixture.PostgreSqlContainer, false, false) { [Fact] public void GivenWrongConnectionString_WhenDocumentSessionIsInitialized_ThenConnectionIsCreated() @@ -81,9 +81,4 @@ private static void ConnectionShouldBeEstablished(IDocumentStore store) result.Should().NotBeNull(); } - - public StoreInitializationTests(MartenFixture fixture) : base(fixture.PostgreSqlContainer, false, false) - { - - } } diff --git a/Marten.Integration.Tests/Tenancy/TenancyPerSchema.cs b/Marten.Integration.Tests/Tenancy/TenancyPerSchema.cs index f25bff443..631e7bd5c 100644 --- a/Marten.Integration.Tests/Tenancy/TenancyPerSchema.cs +++ b/Marten.Integration.Tests/Tenancy/TenancyPerSchema.cs @@ -11,16 +11,11 @@ public interface ITenancyPerSchemaStoreFactory IDocumentStore Get(string? tenantId); } -public class TenancyPerSchemaStoreFactory : IDisposable, ITenancyPerSchemaStoreFactory +public class TenancyPerSchemaStoreFactory(Action configure) + : IDisposable, ITenancyPerSchemaStoreFactory { - private readonly Action configure; private readonly ConcurrentDictionary stores = new (); - public TenancyPerSchemaStoreFactory(Action configure) - { - this.configure = configure; - } - public IDocumentStore Get(string? tenant) { return stores.GetOrAdd(tenant ?? "NO-TENANT", tenantId => @@ -46,17 +41,11 @@ public class DummyTenancyContext public string? TenantId { get; set; } } -public class TenancyPerSchemaSessionFactory: ISessionFactory +public class TenancyPerSchemaSessionFactory( + ITenancyPerSchemaStoreFactory storeFactory, + DummyTenancyContext tenancyContext) + : ISessionFactory { - private readonly ITenancyPerSchemaStoreFactory storeFactory; - private readonly DummyTenancyContext tenancyContext; - - public TenancyPerSchemaSessionFactory(ITenancyPerSchemaStoreFactory storeFactory, DummyTenancyContext tenancyContext) - { - this.storeFactory = storeFactory; - this.tenancyContext = tenancyContext; - } - public IQuerySession QuerySession() { return storeFactory.Get(tenancyContext.TenantId).QuerySession(); @@ -73,16 +62,11 @@ public record TestDocumentForTenancy( string Name ); -public class TenancyPerSchema: MartenTest +public class TenancyPerSchema(MartenFixture fixture): MartenTest(fixture.PostgreSqlContainer, false) { private const string FirstTenant = "Tenant1"; private const string SecondTenant = "Tenant2"; - public TenancyPerSchema(MartenFixture fixture): base(fixture.PostgreSqlContainer, false) - { - - } - [Fact] public void GivenEvents_WhenInlineTransformationIsApplied_ThenReturnsSameNumberOfTransformedItems() { diff --git a/Marten.Integration.Tests/TestsInfrastructure/MartenTest.cs b/Marten.Integration.Tests/TestsInfrastructure/MartenTest.cs index df0bfdb2e..e91ae1e2d 100644 --- a/Marten.Integration.Tests/TestsInfrastructure/MartenTest.cs +++ b/Marten.Integration.Tests/TestsInfrastructure/MartenTest.cs @@ -24,9 +24,12 @@ public class MartenCollection : ICollectionFixture } [Collection("MartenIntegrationTests")] -public abstract class MartenTest: IAsyncLifetime +public abstract class MartenTest( + PostgreSqlContainer postgreSqlContainer, + bool shouldCreateSession = true, + bool useRandomSchema = true) + : IAsyncLifetime { - private PostgreSqlContainer postgreSqlContainer; protected IDocumentSession Session => session ?? throw new InvalidOperationException("Session is not initialised!"); private IDocumentSession? session; @@ -35,16 +38,7 @@ public abstract class MartenTest: IAsyncLifetime protected IEventStore EventStore => Session.Events; - protected readonly string SchemaName; - private readonly bool shouldCreateSession; - - protected MartenTest(PostgreSqlContainer postgreSqlContainer, bool shouldCreateSession = true, bool useRandomSchema = true) - { - this.postgreSqlContainer = postgreSqlContainer; - this.shouldCreateSession = shouldCreateSession; - - SchemaName = useRandomSchema ? "sch" + Guid.NewGuid().ToString().Replace("-", string.Empty) : "EventStore"; - } + protected readonly string SchemaName = useRandomSchema ? "sch" + Guid.NewGuid().ToString().Replace("-", string.Empty) : "EventStore"; protected virtual IDocumentSession CreateSession(Action? storeOptions = null) { diff --git a/Sample/AsyncProjections/SmartHome.Api/Controllers/MotionSensorsController.cs b/Sample/AsyncProjections/SmartHome.Api/Controllers/MotionSensorsController.cs index 6eb7661bf..27b142f62 100644 --- a/Sample/AsyncProjections/SmartHome.Api/Controllers/MotionSensorsController.cs +++ b/Sample/AsyncProjections/SmartHome.Api/Controllers/MotionSensorsController.cs @@ -10,22 +10,12 @@ namespace SmartHome.Api.Controllers; [Route("api/motion-sensors")] -public class MotionSensorsController: Controller +public class MotionSensorsController( + ICommandBus commandBus, + IQueryBus queryBus, + IIdGenerator idGenerator) + : Controller { - private readonly ICommandBus commandBus; - private readonly IQueryBus queryBus; - private readonly IIdGenerator idGenerator; - - public MotionSensorsController( - ICommandBus commandBus, - IQueryBus queryBus, - IIdGenerator idGenerator) - { - this.commandBus = commandBus; - this.queryBus = queryBus; - this.idGenerator = idGenerator; - } - [HttpGet] public Task> Get() { diff --git a/Sample/AsyncProjections/SmartHome.Api/Controllers/TemperatureMeasurementsController.cs b/Sample/AsyncProjections/SmartHome.Api/Controllers/TemperatureMeasurementsController.cs index bcd1997b5..38e3325cd 100644 --- a/Sample/AsyncProjections/SmartHome.Api/Controllers/TemperatureMeasurementsController.cs +++ b/Sample/AsyncProjections/SmartHome.Api/Controllers/TemperatureMeasurementsController.cs @@ -10,22 +10,12 @@ namespace SmartHome.Api.Controllers; [Route("api/temperature-measurements")] -public class TemperatureMeasurementsController: Controller +public class TemperatureMeasurementsController( + ICommandBus commandBus, + IQueryBus queryBus, + IIdGenerator idGenerator) + : Controller { - private readonly ICommandBus commandBus; - private readonly IQueryBus queryBus; - private readonly IIdGenerator idGenerator; - - public TemperatureMeasurementsController( - ICommandBus commandBus, - IQueryBus queryBus, - IIdGenerator idGenerator) - { - this.commandBus = commandBus; - this.queryBus = queryBus; - this.idGenerator = idGenerator; - } - [HttpGet] public Task> Get() => queryBus.Query>( diff --git a/Sample/AsyncProjections/SmartHome.Temperature/MotionSensors/GettingMotionSensor/GetMotionSensor.cs b/Sample/AsyncProjections/SmartHome.Temperature/MotionSensors/GettingMotionSensor/GetMotionSensor.cs index f1f147111..50ee938d8 100644 --- a/Sample/AsyncProjections/SmartHome.Temperature/MotionSensors/GettingMotionSensor/GetMotionSensor.cs +++ b/Sample/AsyncProjections/SmartHome.Temperature/MotionSensors/GettingMotionSensor/GetMotionSensor.cs @@ -10,15 +10,9 @@ public class GetMotionSensors public static GetMotionSensors Create() => new(); } -public class HandleGetMotionSensors : IQueryHandler> +public class HandleGetMotionSensors(IDocumentSession querySession) + : IQueryHandler> { - private readonly IDocumentSession querySession; - - public HandleGetMotionSensors(IDocumentSession querySession) - { - this.querySession = querySession; - } - public Task> Handle(GetMotionSensors request, CancellationToken cancellationToken) { return querySession.Query().ToListAsync(cancellationToken); diff --git a/Sample/AsyncProjections/SmartHome.Temperature/MotionSensors/InstallingMotionSensor/InstallMotionSensor.cs b/Sample/AsyncProjections/SmartHome.Temperature/MotionSensors/InstallingMotionSensor/InstallMotionSensor.cs index b3c420a76..4b70d9bfd 100644 --- a/Sample/AsyncProjections/SmartHome.Temperature/MotionSensors/InstallingMotionSensor/InstallMotionSensor.cs +++ b/Sample/AsyncProjections/SmartHome.Temperature/MotionSensors/InstallingMotionSensor/InstallMotionSensor.cs @@ -18,14 +18,9 @@ Guid motionSensorId } } -public class HandleInstallMotionSensor: +public class HandleInstallMotionSensor(IMartenRepository repository): ICommandHandler { - private readonly IMartenRepository repository; - - public HandleInstallMotionSensor(IMartenRepository repository) => - this.repository = repository; - public Task Handle(InstallMotionSensor command, CancellationToken ct) => repository.Add( MotionSensor.Install( diff --git a/Sample/AsyncProjections/SmartHome.Temperature/MotionSensors/RebuildingMotionSensorsViews/RebuildMotionSensorsViews.cs b/Sample/AsyncProjections/SmartHome.Temperature/MotionSensors/RebuildingMotionSensorsViews/RebuildMotionSensorsViews.cs index dc2cbd521..cfc8614b3 100644 --- a/Sample/AsyncProjections/SmartHome.Temperature/MotionSensors/RebuildingMotionSensorsViews/RebuildMotionSensorsViews.cs +++ b/Sample/AsyncProjections/SmartHome.Temperature/MotionSensors/RebuildingMotionSensorsViews/RebuildMotionSensorsViews.cs @@ -5,18 +5,9 @@ namespace SmartHome.Temperature.MotionSensors.RebuildingMotionSensorsViews; public record RebuildMotionSensorsViews; -public class HandleRebuildMotionSensorsViews : +public class HandleRebuildMotionSensorsViews(IDocumentSession session): ICommandHandler { - private readonly IDocumentSession session; - - public HandleRebuildMotionSensorsViews( - IDocumentSession session - ) - { - this.session = session; - } - public async Task Handle(RebuildMotionSensorsViews command, CancellationToken ct) { using var daemon = await session.DocumentStore.BuildProjectionDaemonAsync(); diff --git a/Sample/AsyncProjections/SmartHome.Temperature/TemperatureMeasurements/GettingTemperatureMeasurements/GetTemperatureMeasurements.cs b/Sample/AsyncProjections/SmartHome.Temperature/TemperatureMeasurements/GettingTemperatureMeasurements/GetTemperatureMeasurements.cs index 2c70f3c89..a526f3379 100644 --- a/Sample/AsyncProjections/SmartHome.Temperature/TemperatureMeasurements/GettingTemperatureMeasurements/GetTemperatureMeasurements.cs +++ b/Sample/AsyncProjections/SmartHome.Temperature/TemperatureMeasurements/GettingTemperatureMeasurements/GetTemperatureMeasurements.cs @@ -5,15 +5,9 @@ namespace SmartHome.Temperature.TemperatureMeasurements.GettingTemperatureMeasur public record GetTemperatureMeasurements; -public class HandleGetTemperatureMeasurements: IQueryHandler> +public class HandleGetTemperatureMeasurements(IDocumentSession querySession) + : IQueryHandler> { - private readonly IDocumentSession querySession; - - public HandleGetTemperatureMeasurements(IDocumentSession querySession) - { - this.querySession = querySession; - } - public Task> Handle(GetTemperatureMeasurements request, CancellationToken cancellationToken) { return querySession.Query().ToListAsync(cancellationToken); diff --git a/Sample/AsyncProjections/SmartHome.Temperature/TemperatureMeasurements/RecordingTemperature/RecordTemperature.cs b/Sample/AsyncProjections/SmartHome.Temperature/TemperatureMeasurements/RecordingTemperature/RecordTemperature.cs index baba6939f..b73ab28f8 100644 --- a/Sample/AsyncProjections/SmartHome.Temperature/TemperatureMeasurements/RecordingTemperature/RecordTemperature.cs +++ b/Sample/AsyncProjections/SmartHome.Temperature/TemperatureMeasurements/RecordingTemperature/RecordTemperature.cs @@ -19,14 +19,9 @@ public static RecordTemperature Create(Guid measurementId, decimal temperature) } } -public class HandleRecordTemperature: +public class HandleRecordTemperature(IMartenRepository repository): ICommandHandler { - private readonly IMartenRepository repository; - - public HandleRecordTemperature(IMartenRepository repository) => - this.repository = repository; - public Task Handle(RecordTemperature command, CancellationToken ct) { var (measurementId, temperature) = command; diff --git a/Sample/AsyncProjections/SmartHome.Temperature/TemperatureMeasurements/StartingTemperatureMeasurement/StartTemperatureMeasurement.cs b/Sample/AsyncProjections/SmartHome.Temperature/TemperatureMeasurements/StartingTemperatureMeasurement/StartTemperatureMeasurement.cs index 40977c3a4..0b5af4e38 100644 --- a/Sample/AsyncProjections/SmartHome.Temperature/TemperatureMeasurements/StartingTemperatureMeasurement/StartTemperatureMeasurement.cs +++ b/Sample/AsyncProjections/SmartHome.Temperature/TemperatureMeasurements/StartingTemperatureMeasurement/StartTemperatureMeasurement.cs @@ -16,14 +16,9 @@ public static StartTemperatureMeasurement Create(Guid measurementId) } } -public class HandleStartTemperatureMeasurement: +public class HandleStartTemperatureMeasurement(IMartenRepository repository): ICommandHandler { - private readonly IMartenRepository repository; - - public HandleStartTemperatureMeasurement(IMartenRepository repository) => - this.repository = repository; - public Task Handle(StartTemperatureMeasurement command, CancellationToken ct) => repository.Add( TemperatureMeasurement.Start( diff --git a/Sample/CRUDToCQRS/01-CRUD/ECommerce/Controllers/ProductsController.cs b/Sample/CRUDToCQRS/01-CRUD/ECommerce/Controllers/ProductsController.cs index ae0712fc3..46603fbe6 100644 --- a/Sample/CRUDToCQRS/01-CRUD/ECommerce/Controllers/ProductsController.cs +++ b/Sample/CRUDToCQRS/01-CRUD/ECommerce/Controllers/ProductsController.cs @@ -10,7 +10,7 @@ namespace ECommerce.Controllers; [Route("api/[controller]")] public class ProductsController: CRUDController { - public ProductsController(ProductService service): base(service) + public ProductsController(ProductService service):base(service) { } diff --git a/Sample/CRUDToCQRS/01-CRUD/ECommerce/Core/Controllers/CRUDController.cs b/Sample/CRUDToCQRS/01-CRUD/ECommerce/Core/Controllers/CRUDController.cs index 00fc95d58..fc5bf7619 100644 --- a/Sample/CRUDToCQRS/01-CRUD/ECommerce/Core/Controllers/CRUDController.cs +++ b/Sample/CRUDToCQRS/01-CRUD/ECommerce/Core/Controllers/CRUDController.cs @@ -5,14 +5,9 @@ namespace ECommerce.Core.Controllers; -public abstract class CRUDController: Controller +public abstract class CRUDController(ICRUDService service): Controller { - protected readonly ICRUDService service; - - protected CRUDController(ICRUDService service) - { - this.service = service; - } + protected readonly ICRUDService service = service; protected async Task CreateAsync( TCreateRequest request, diff --git a/Sample/CRUDToCQRS/01-CRUD/ECommerce/Core/Services/CRUDService.cs b/Sample/CRUDToCQRS/01-CRUD/ECommerce/Core/Services/CRUDService.cs index 756c7cac1..7f5895636 100644 --- a/Sample/CRUDToCQRS/01-CRUD/ECommerce/Core/Services/CRUDService.cs +++ b/Sample/CRUDToCQRS/01-CRUD/ECommerce/Core/Services/CRUDService.cs @@ -7,18 +7,9 @@ namespace ECommerce.Core.Services; -public abstract class CRUDService: ICRUDService +public abstract class CRUDService(ICRUDRepository repository, IMapper mapper): ICRUDService where TEntity : class, IEntity, new() { - private readonly ICRUDRepository repository; - private readonly IMapper mapper; - - protected CRUDService(ICRUDRepository repository, IMapper mapper) - { - this.repository = repository; - this.mapper = mapper; - } - public async Task CreateAsync( TCreateRequest request, CancellationToken ct diff --git a/Sample/CRUDToCQRS/01-CRUD/ECommerce/Repositories/ProductRepository.cs b/Sample/CRUDToCQRS/01-CRUD/ECommerce/Repositories/ProductRepository.cs index f9b153e1e..97b11084f 100644 --- a/Sample/CRUDToCQRS/01-CRUD/ECommerce/Repositories/ProductRepository.cs +++ b/Sample/CRUDToCQRS/01-CRUD/ECommerce/Repositories/ProductRepository.cs @@ -4,9 +4,4 @@ namespace ECommerce.Repositories; -public class ProductRepository: CRUDRepository -{ - public ProductRepository(ECommerceDbContext dbContext) : base(dbContext) - { - } -} +public class ProductRepository(ECommerceDbContext dbContext): CRUDRepository(dbContext); diff --git a/Sample/CRUDToCQRS/01-CRUD/ECommerce/Services/ProductService.cs b/Sample/CRUDToCQRS/01-CRUD/ECommerce/Services/ProductService.cs index 2d31c1c60..4a7115344 100644 --- a/Sample/CRUDToCQRS/01-CRUD/ECommerce/Services/ProductService.cs +++ b/Sample/CRUDToCQRS/01-CRUD/ECommerce/Services/ProductService.cs @@ -5,9 +5,4 @@ namespace ECommerce.Services; -public class ProductService: CRUDService -{ - public ProductService(ProductRepository repository, IMapper mapper) : base(repository, mapper) - { - } -} +public class ProductService(ProductRepository repository, IMapper mapper): CRUDService(repository, mapper); diff --git a/Sample/CRUDToCQRS/01-CRUD/ECommerce/Storage/ECommerceDbContext.cs b/Sample/CRUDToCQRS/01-CRUD/ECommerce/Storage/ECommerceDbContext.cs index cdf1e7e58..053eba7a5 100644 --- a/Sample/CRUDToCQRS/01-CRUD/ECommerce/Storage/ECommerceDbContext.cs +++ b/Sample/CRUDToCQRS/01-CRUD/ECommerce/Storage/ECommerceDbContext.cs @@ -3,14 +3,8 @@ namespace ECommerce.Storage; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; -public class ECommerceDbContext: DbContext +public class ECommerceDbContext(DbContextOptions options): DbContext(options) { - public ECommerceDbContext(DbContextOptions options) - : base(options) - { - - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Controllers/ProductsController.cs b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Controllers/ProductsController.cs index 2569212a3..7c773050d 100644 --- a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Controllers/ProductsController.cs +++ b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Controllers/ProductsController.cs @@ -9,15 +9,11 @@ namespace ECommerce.Controllers; [ApiController] [Route("api/[controller]")] -public class ProductsController: CRUDController +public class ProductsController(ProductService service, ProductReadOnlyService readOnlyService) + : CRUDController(service, readOnlyService) { protected override Func GetEntityByIdUri { get; } = id => $"/api/Products/{id}"; - public ProductsController(ProductService service, ProductReadOnlyService readOnlyService) - : base(service, readOnlyService) - { - } - [HttpPost] public Task CreateAsync( [FromBody] CreateProductRequest request, diff --git a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Controllers/CRUDController.cs b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Controllers/CRUDController.cs index d5fdb19a8..adaded948 100644 --- a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Controllers/CRUDController.cs +++ b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Controllers/CRUDController.cs @@ -4,21 +4,16 @@ namespace ECommerce.Core.Controllers; -public abstract class CRUDController: Controller where TEntity : class, IEntity, new() +public abstract class CRUDController( + IService service, + IReadOnlyService readOnlyService) + : Controller + where TEntity : class, IEntity, new() { - protected readonly IService Service; - protected readonly IReadOnlyService ReadOnlyService; + protected readonly IService Service = service; + protected readonly IReadOnlyService ReadOnlyService = readOnlyService; protected abstract Func GetEntityByIdUri { get; } - protected CRUDController( - IService service, - IReadOnlyService readOnlyService - ) - { - Service = service; - ReadOnlyService = readOnlyService; - } - protected async Task CreateAsync( TCreateRequest request, CancellationToken ct diff --git a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Repositories/ReadOnlyRepository.cs b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Repositories/ReadOnlyRepository.cs index 9730e7e5a..97a4f9f9c 100644 --- a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Repositories/ReadOnlyRepository.cs +++ b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Repositories/ReadOnlyRepository.cs @@ -2,16 +2,9 @@ namespace ECommerce.Core.Repositories; -public abstract class ReadOnlyRepository: IReadonlyRepository +public abstract class ReadOnlyRepository(IQueryable query): IReadonlyRepository where TEntity : class, IEntity { - private readonly IQueryable query; - - protected ReadOnlyRepository(IQueryable query) - { - this.query = query; - } - public Task FindByIdAsync(Guid id, CancellationToken ct) { return query.SingleOrDefaultAsync(e => e.Id == id, ct); diff --git a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Repositories/Repository.cs b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Repositories/Repository.cs index c483fb08a..52e24300b 100644 --- a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Repositories/Repository.cs +++ b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Repositories/Repository.cs @@ -2,16 +2,9 @@ namespace ECommerce.Core.Repositories; -public abstract class Repository: IRepository +public abstract class Repository(DbContext dbContext): IRepository where TEntity : class, IEntity { - private readonly DbContext dbContext; - - protected Repository(DbContext dbContext) - { - this.dbContext = dbContext; - } - public void Add(TEntity entity) { if (entity == null) diff --git a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Services/ReadOnlyOnlyService.cs b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Services/ReadOnlyOnlyService.cs index fd6796ce9..66ed29b97 100644 --- a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Services/ReadOnlyOnlyService.cs +++ b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Services/ReadOnlyOnlyService.cs @@ -5,18 +5,10 @@ namespace ECommerce.Core.Services; -public abstract class ReadOnlyOnlyService: IReadOnlyService +public abstract class ReadOnlyOnlyService(IReadonlyRepository repository, IMapper mapper) + : IReadOnlyService where TEntity : class, IEntity, new() { - private readonly IReadonlyRepository repository; - private readonly IMapper mapper; - - protected ReadOnlyOnlyService(IReadonlyRepository repository, IMapper mapper) - { - this.repository = repository; - this.mapper = mapper; - } - public async Task GetByIdAsync(Guid id, CancellationToken ct) { return mapper.Map(await GetEntityByIdAsync(id, ct)); diff --git a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Services/Service.cs b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Services/Service.cs index 2faf5f118..87615bce7 100644 --- a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Services/Service.cs +++ b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Core/Services/Service.cs @@ -4,18 +4,9 @@ namespace ECommerce.Core.Services; -public class Service: IService +public class Service(IRepository repository, IMapper mapper): IService where TEntity : class, IEntity, new() { - private readonly IRepository repository; - private readonly IMapper mapper; - - public Service(IRepository repository, IMapper mapper) - { - this.repository = repository; - this.mapper = mapper; - } - public Task CreateAsync(TCreateRequest request, CancellationToken ct) { diff --git a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Repositories/ProductReadOnlyRepository.cs b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Repositories/ProductReadOnlyRepository.cs index 4ba07563d..63810ad55 100644 --- a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Repositories/ProductReadOnlyRepository.cs +++ b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Repositories/ProductReadOnlyRepository.cs @@ -4,9 +4,4 @@ namespace ECommerce.Repositories; -public class ProductReadOnlyRepository: ReadOnlyRepository -{ - public ProductReadOnlyRepository(IQueryable query) : base(query) - { - } -} +public class ProductReadOnlyRepository(IQueryable query): ReadOnlyRepository(query); diff --git a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Repositories/ProductRepository.cs b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Repositories/ProductRepository.cs index 6dc80bcee..a1c7a0e79 100644 --- a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Repositories/ProductRepository.cs +++ b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Repositories/ProductRepository.cs @@ -4,9 +4,4 @@ namespace ECommerce.Repositories; -public class ProductRepository: Repository -{ - public ProductRepository(ECommerceDbContext dbContext) : base(dbContext) - { - } -} +public class ProductRepository(ECommerceDbContext dbContext): Repository(dbContext); diff --git a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Services/ProductReadOnlyService.cs b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Services/ProductReadOnlyService.cs index 668c6db50..03fa6f93a 100644 --- a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Services/ProductReadOnlyService.cs +++ b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Services/ProductReadOnlyService.cs @@ -5,9 +5,5 @@ namespace ECommerce.Services; -public class ProductReadOnlyService: ReadOnlyOnlyService -{ - public ProductReadOnlyService(ProductReadOnlyRepository repository, IMapper mapper) : base(repository, mapper) - { - } -} +public class ProductReadOnlyService(ProductReadOnlyRepository repository, IMapper mapper) + : ReadOnlyOnlyService(repository, mapper); diff --git a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Services/ProductService.cs b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Services/ProductService.cs index ac9340c23..12d776855 100644 --- a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Services/ProductService.cs +++ b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Services/ProductService.cs @@ -5,9 +5,4 @@ namespace ECommerce.Services; -public class ProductService: Service -{ - public ProductService(ProductRepository repository, IMapper mapper) : base(repository, mapper) - { - } -} +public class ProductService(ProductRepository repository, IMapper mapper): Service(repository, mapper); diff --git a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Storage/ECommerceDbContext.cs b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Storage/ECommerceDbContext.cs index cdf1e7e58..053eba7a5 100644 --- a/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Storage/ECommerceDbContext.cs +++ b/Sample/CRUDToCQRS/02-CRUDWithCQRS/ECommerce/Storage/ECommerceDbContext.cs @@ -3,14 +3,8 @@ namespace ECommerce.Storage; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; -public class ECommerceDbContext: DbContext +public class ECommerceDbContext(DbContextOptions options): DbContext(options) { - public ECommerceDbContext(DbContextOptions options) - : base(options) - { - - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Repositories/ReadOnlyRepository.cs b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Repositories/ReadOnlyRepository.cs index cc50a5575..502078477 100644 --- a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Repositories/ReadOnlyRepository.cs +++ b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Repositories/ReadOnlyRepository.cs @@ -3,16 +3,9 @@ namespace ECommerce.Domain.Core.Repositories; -public abstract class ReadOnlyRepository: IReadonlyRepository +public abstract class ReadOnlyRepository(IQueryable query): IReadonlyRepository where TEntity : class, IEntity { - private readonly IQueryable query; - - protected ReadOnlyRepository(IQueryable query) - { - this.query = query; - } - public Task FindByIdAsync(Guid id, CancellationToken ct) { return query.SingleOrDefaultAsync(e => e.Id == id, ct); diff --git a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Repositories/Repository.cs b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Repositories/Repository.cs index 6d2e5fcd6..40d147ee8 100644 --- a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Repositories/Repository.cs +++ b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Repositories/Repository.cs @@ -3,16 +3,9 @@ namespace ECommerce.Domain.Core.Repositories; -public abstract class Repository: IRepository +public abstract class Repository(DbContext dbContext): IRepository where TEntity : class, IEntity { - private readonly DbContext dbContext; - - protected Repository(DbContext dbContext) - { - this.dbContext = dbContext; - } - public void Add(TEntity entity) { if (entity == null) diff --git a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Services/ReadOnlyOnlyService.cs b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Services/ReadOnlyOnlyService.cs index 7a3e85023..96356fe98 100644 --- a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Services/ReadOnlyOnlyService.cs +++ b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Services/ReadOnlyOnlyService.cs @@ -6,18 +6,10 @@ namespace ECommerce.Domain.Core.Services; -public abstract class ReadOnlyOnlyService: IReadOnlyService +public abstract class ReadOnlyOnlyService(IReadonlyRepository repository, IMapper mapper) + : IReadOnlyService where TEntity : class, IEntity, new() { - private readonly IReadonlyRepository repository; - private readonly IMapper mapper; - - protected ReadOnlyOnlyService(IReadonlyRepository repository, IMapper mapper) - { - this.repository = repository; - this.mapper = mapper; - } - public async Task GetByIdAsync(Guid id, CancellationToken ct) { return mapper.Map(await GetEntityByIdAsync(id, ct)); diff --git a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Services/Service.cs b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Services/Service.cs index 4f638a8c0..d9b3af4c3 100644 --- a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Services/Service.cs +++ b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Core/Services/Service.cs @@ -5,18 +5,9 @@ namespace ECommerce.Domain.Core.Services; -public class Service: IService +public class Service(IRepository repository, IMapper mapper): IService where TEntity : class, IEntity, new() { - private readonly IRepository repository; - private readonly IMapper mapper; - - public Service(IRepository repository, IMapper mapper) - { - this.repository = repository; - this.mapper = mapper; - } - public Task CreateAsync(TCreateRequest request, CancellationToken ct) { diff --git a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Repositories/ProductReadOnlyRepository.cs b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Repositories/ProductReadOnlyRepository.cs index 0a7eb6a4a..c68f713d4 100644 --- a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Repositories/ProductReadOnlyRepository.cs +++ b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Repositories/ProductReadOnlyRepository.cs @@ -3,9 +3,4 @@ namespace ECommerce.Domain.Products.Repositories; -public class ProductReadOnlyRepository: ReadOnlyRepository -{ - public ProductReadOnlyRepository(IQueryable query) : base(query) - { - } -} +public class ProductReadOnlyRepository(IQueryable query): ReadOnlyRepository(query); diff --git a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Repositories/ProductRepository.cs b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Repositories/ProductRepository.cs index 85235670c..604df60ce 100644 --- a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Repositories/ProductRepository.cs +++ b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Repositories/ProductRepository.cs @@ -4,9 +4,4 @@ namespace ECommerce.Domain.Products.Repositories; -public class ProductRepository: Repository -{ - public ProductRepository(ECommerceDbContext dbContext) : base(dbContext) - { - } -} +public class ProductRepository(ECommerceDbContext dbContext): Repository(dbContext); diff --git a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Services/ProductReadOnlyService.cs b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Services/ProductReadOnlyService.cs index 7a51ca92a..8b1231eb6 100644 --- a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Services/ProductReadOnlyService.cs +++ b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Services/ProductReadOnlyService.cs @@ -5,9 +5,5 @@ namespace ECommerce.Domain.Products.Services; -public class ProductReadOnlyService: ReadOnlyOnlyService -{ - public ProductReadOnlyService(ProductReadOnlyRepository repository, IMapper mapper) : base(repository, mapper) - { - } -} +public class ProductReadOnlyService(ProductReadOnlyRepository repository, IMapper mapper) + : ReadOnlyOnlyService(repository, mapper); diff --git a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Services/ProductService.cs b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Services/ProductService.cs index d076739d0..07856f8fc 100644 --- a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Services/ProductService.cs +++ b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Products/Services/ProductService.cs @@ -5,9 +5,4 @@ namespace ECommerce.Domain.Products.Services; -public class ProductService: Service -{ - public ProductService(ProductRepository repository, IMapper mapper) : base(repository, mapper) - { - } -} +public class ProductService(ProductRepository repository, IMapper mapper): Service(repository, mapper); diff --git a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Storage/ECommerceDbContext.cs b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Storage/ECommerceDbContext.cs index e0cbc00ea..e1973e74a 100644 --- a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Storage/ECommerceDbContext.cs +++ b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce.Domain/Storage/ECommerceDbContext.cs @@ -4,14 +4,8 @@ namespace ECommerce.Domain.Storage; -public class ECommerceDbContext: DbContext +public class ECommerceDbContext(DbContextOptions options): DbContext(options) { - public ECommerceDbContext(DbContextOptions options) - : base(options) - { - - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce/Controllers/ProductsController.cs b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce/Controllers/ProductsController.cs index 76d67cdc7..29d875e47 100644 --- a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce/Controllers/ProductsController.cs +++ b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce/Controllers/ProductsController.cs @@ -9,15 +9,11 @@ namespace ECommerce.Controllers; [ApiController] [Route("api/[controller]")] -public class ProductsController: CRUDController +public class ProductsController(ProductService service, ProductReadOnlyService readOnlyService) + : CRUDController(service, readOnlyService) { protected override Func GetEntityByIdUri { get; } = id => $"/api/Products/{id}"; - public ProductsController(ProductService service, ProductReadOnlyService readOnlyService) - : base(service, readOnlyService) - { - } - [HttpPost] public Task CreateAsync( [FromBody] CreateProductRequest request, diff --git a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce/Core/Controllers/CRUDController.cs b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce/Core/Controllers/CRUDController.cs index 5f21dba62..4fac5e8c2 100644 --- a/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce/Core/Controllers/CRUDController.cs +++ b/Sample/CRUDToCQRS/03-DomainGrouping/ECommerce/Core/Controllers/CRUDController.cs @@ -5,21 +5,16 @@ namespace ECommerce.Core.Controllers; -public abstract class CRUDController: Controller where TEntity : class, IEntity, new() +public abstract class CRUDController( + IService service, + IReadOnlyService readOnlyService) + : Controller + where TEntity : class, IEntity, new() { - protected readonly IService Service; - protected readonly IReadOnlyService ReadOnlyService; + protected readonly IService Service = service; + protected readonly IReadOnlyService ReadOnlyService = readOnlyService; protected abstract Func GetEntityByIdUri { get; } - protected CRUDController( - IService service, - IReadOnlyService readOnlyService - ) - { - Service = service; - ReadOnlyService = readOnlyService; - } - protected async Task CreateAsync( TCreateRequest request, CancellationToken ct diff --git a/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Core/Services/ReadOnlyOnlyService.cs b/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Core/Services/ReadOnlyOnlyService.cs index b78329738..ad23d9e21 100644 --- a/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Core/Services/ReadOnlyOnlyService.cs +++ b/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Core/Services/ReadOnlyOnlyService.cs @@ -6,18 +6,9 @@ namespace ECommerce.Domain.Core.Services; -public abstract class ReadOnlyOnlyService: IReadOnlyService +public abstract class ReadOnlyOnlyService(IQueryable query, IMapper mapper): IReadOnlyService where TEntity : class, IEntity, new() { - private readonly IQueryable query; - private readonly IMapper mapper; - - protected ReadOnlyOnlyService(IQueryable query, IMapper mapper) - { - this.query = query; - this.mapper = mapper; - } - public async Task GetByIdAsync(Guid id, CancellationToken ct) { return mapper.Map(await GetEntityByIdAsync(id, ct)); diff --git a/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Core/Services/Service.cs b/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Core/Services/Service.cs index af9f26bfb..b605cc9d0 100644 --- a/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Core/Services/Service.cs +++ b/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Core/Services/Service.cs @@ -6,17 +6,10 @@ namespace ECommerce.Domain.Core.Services; -public abstract class Service: IService +public abstract class Service(DbContext dbContext, IMapper mapper): IService where TEntity : class, IEntity, new() { - protected readonly DbContext dbContext; - private readonly IMapper mapper; - - protected Service(DbContext dbContext, IMapper mapper) - { - this.dbContext = dbContext; - this.mapper = mapper; - } + protected readonly DbContext dbContext = dbContext; public Task CreateAsync( TCreateRequest request, diff --git a/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Products/Services/ProductReadOnlyService.cs b/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Products/Services/ProductReadOnlyService.cs index bf68b4152..c2664aaf0 100644 --- a/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Products/Services/ProductReadOnlyService.cs +++ b/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Products/Services/ProductReadOnlyService.cs @@ -4,9 +4,5 @@ namespace ECommerce.Domain.Products.Services; -public class ProductReadOnlyService: ReadOnlyOnlyService -{ - public ProductReadOnlyService(IQueryable query, IMapper mapper) : base(query, mapper) - { - } -} +public class ProductReadOnlyService(IQueryable query, IMapper mapper) + : ReadOnlyOnlyService(query, mapper); diff --git a/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Products/Services/ProductService.cs b/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Products/Services/ProductService.cs index d801ba2b9..8dd4d6aab 100644 --- a/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Products/Services/ProductService.cs +++ b/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Products/Services/ProductService.cs @@ -5,9 +5,4 @@ namespace ECommerce.Domain.Products.Services; -public class ProductService: Service -{ - public ProductService(ECommerceDbContext dbContext, IMapper mapper) : base(dbContext, mapper) - { - } -} +public class ProductService(ECommerceDbContext dbContext, IMapper mapper): Service(dbContext, mapper); diff --git a/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Storage/ECommerceDbContext.cs b/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Storage/ECommerceDbContext.cs index e0cbc00ea..e1973e74a 100644 --- a/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Storage/ECommerceDbContext.cs +++ b/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce.Domain/Storage/ECommerceDbContext.cs @@ -4,14 +4,8 @@ namespace ECommerce.Domain.Storage; -public class ECommerceDbContext: DbContext +public class ECommerceDbContext(DbContextOptions options): DbContext(options) { - public ECommerceDbContext(DbContextOptions options) - : base(options) - { - - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce/Controllers/ProductsController.cs b/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce/Controllers/ProductsController.cs index c3eb4a55c..9bca9b5a9 100644 --- a/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce/Controllers/ProductsController.cs +++ b/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce/Controllers/ProductsController.cs @@ -9,15 +9,11 @@ namespace ECommerce.Controllers; [ApiController] [Route("api/[controller]")] -public class ProductsController: CRUDController +public class ProductsController(ProductService service, ProductReadOnlyService readOnlyService) + : CRUDController(service, readOnlyService) { protected override Func GetEntityByIdUri { get; } = id => $"/api/Products/{id}"; - public ProductsController(ProductService service, ProductReadOnlyService readOnlyService) - : base(service, readOnlyService) - { - } - [HttpPost] public Task CreateAsync( [FromBody] CreateProductRequest request, diff --git a/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce/Core/Controllers/CRUDController.cs b/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce/Core/Controllers/CRUDController.cs index 5f21dba62..4fac5e8c2 100644 --- a/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce/Core/Controllers/CRUDController.cs +++ b/Sample/CRUDToCQRS/04-SlimmedDomain/ECommerce/Core/Controllers/CRUDController.cs @@ -5,21 +5,16 @@ namespace ECommerce.Core.Controllers; -public abstract class CRUDController: Controller where TEntity : class, IEntity, new() +public abstract class CRUDController( + IService service, + IReadOnlyService readOnlyService) + : Controller + where TEntity : class, IEntity, new() { - protected readonly IService Service; - protected readonly IReadOnlyService ReadOnlyService; + protected readonly IService Service = service; + protected readonly IReadOnlyService ReadOnlyService = readOnlyService; protected abstract Func GetEntityByIdUri { get; } - protected CRUDController( - IService service, - IReadOnlyService readOnlyService - ) - { - Service = service; - ReadOnlyService = readOnlyService; - } - protected async Task CreateAsync( TCreateRequest request, CancellationToken ct diff --git a/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce.Domain/Products/Services/ProductReadOnlyService.cs b/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce.Domain/Products/Services/ProductReadOnlyService.cs index 82c8aff45..4cc9445f1 100644 --- a/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce.Domain/Products/Services/ProductReadOnlyService.cs +++ b/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce.Domain/Products/Services/ProductReadOnlyService.cs @@ -5,12 +5,8 @@ namespace ECommerce.Domain.Products.Services; -public class ProductReadOnlyService +public class ProductReadOnlyService(IQueryable query) { - private readonly IQueryable query; - - public ProductReadOnlyService(IQueryable query) => this.query = query; - public Task GetByIdAsync(Guid id, CancellationToken ct) { return query diff --git a/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce.Domain/Products/Services/ProductService.cs b/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce.Domain/Products/Services/ProductService.cs index 80456c083..b26ef0ff5 100644 --- a/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce.Domain/Products/Services/ProductService.cs +++ b/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce.Domain/Products/Services/ProductService.cs @@ -5,15 +5,8 @@ namespace ECommerce.Domain.Products.Services; -public class ProductService +public class ProductService(ECommerceDbContext dbContext) { - private readonly ECommerceDbContext dbContext; - - public ProductService(ECommerceDbContext dbContext) - { - this.dbContext = dbContext; - } - public Task CreateAsync( CreateProductRequest command, CancellationToken ct diff --git a/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce.Domain/Storage/ECommerceDbContext.cs b/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce.Domain/Storage/ECommerceDbContext.cs index e0cbc00ea..e1973e74a 100644 --- a/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce.Domain/Storage/ECommerceDbContext.cs +++ b/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce.Domain/Storage/ECommerceDbContext.cs @@ -4,14 +4,8 @@ namespace ECommerce.Domain.Storage; -public class ECommerceDbContext: DbContext +public class ECommerceDbContext(DbContextOptions options): DbContext(options) { - public ECommerceDbContext(DbContextOptions options) - : base(options) - { - - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce/Controllers/ProductsController.cs b/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce/Controllers/ProductsController.cs index 493850d07..ff91d3c06 100644 --- a/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce/Controllers/ProductsController.cs +++ b/Sample/CRUDToCQRS/05-ExplicitDomain/ECommerce/Controllers/ProductsController.cs @@ -8,17 +8,9 @@ namespace ECommerce.Controllers; [ApiController] [Route("api/[controller]")] -public class ProductsController: Controller +public class ProductsController(ProductService service, ProductReadOnlyService readOnlyService) + : Controller { - private readonly ProductService service; - private readonly ProductReadOnlyService readOnlyService; - - public ProductsController(ProductService service, ProductReadOnlyService readOnlyService) - { - this.service = service; - this.readOnlyService = readOnlyService; - } - [HttpPost] public async Task CreateAsync( [FromBody] CreateProductRequest request, diff --git a/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce.Domain/Products/ProductReadOnlyService.cs b/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce.Domain/Products/ProductReadOnlyService.cs index f242782b4..0f19d171e 100644 --- a/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce.Domain/Products/ProductReadOnlyService.cs +++ b/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce.Domain/Products/ProductReadOnlyService.cs @@ -6,12 +6,8 @@ namespace ECommerce.Domain.Products; using static GetProductByIdHandler; using static GetProductsHandler; -public class ProductReadOnlyService +public class ProductReadOnlyService(IQueryable products) { - private readonly IQueryable products; - - public ProductReadOnlyService(IQueryable products) => this.products = products; - public Task GetByIdAsync(GetProductById query, CancellationToken ct) => products.HandleAsync(query, ct); diff --git a/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce.Domain/Products/ProductService.cs b/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce.Domain/Products/ProductService.cs index 399bc03bd..e5a471c96 100644 --- a/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce.Domain/Products/ProductService.cs +++ b/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce.Domain/Products/ProductService.cs @@ -8,15 +8,8 @@ namespace ECommerce.Domain.Products; using static CreateProductHandler; using static UpdateProductHandler; -public class ProductService +public class ProductService(ECommerceDbContext dbContext) { - private readonly ECommerceDbContext dbContext; - - public ProductService(ECommerceDbContext dbContext) - { - this.dbContext = dbContext; - } - public Task CreateAsync(CreateProduct command, CancellationToken ct) => dbContext.AddAndSaveChanges( Handle(command), diff --git a/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce.Domain/Storage/ECommerceDbContext.cs b/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce.Domain/Storage/ECommerceDbContext.cs index e0cbc00ea..e1973e74a 100644 --- a/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce.Domain/Storage/ECommerceDbContext.cs +++ b/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce.Domain/Storage/ECommerceDbContext.cs @@ -4,14 +4,8 @@ namespace ECommerce.Domain.Storage; -public class ECommerceDbContext: DbContext +public class ECommerceDbContext(DbContextOptions options): DbContext(options) { - public ECommerceDbContext(DbContextOptions options) - : base(options) - { - - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce/Controllers/ProductsController.cs b/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce/Controllers/ProductsController.cs index 072b4fbae..f0428d3b8 100644 --- a/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce/Controllers/ProductsController.cs +++ b/Sample/CRUDToCQRS/06-SlicedDomain/ECommerce/Controllers/ProductsController.cs @@ -9,17 +9,9 @@ namespace ECommerce.Controllers; [ApiController] [Route("api/[controller]")] -public class ProductsController: Controller +public class ProductsController(ProductService service, ProductReadOnlyService readOnlyService) + : Controller { - private readonly ProductService service; - private readonly ProductReadOnlyService readOnlyService; - - public ProductsController(ProductService service, ProductReadOnlyService readOnlyService) - { - this.service = service; - this.readOnlyService = readOnlyService; - } - [HttpPost] public async Task CreateAsync( [FromBody] CreateProductRequest request, diff --git a/Sample/CRUDToCQRS/07-FlattenedLayers/ECommerce.Domain/Storage/ECommerceDbContext.cs b/Sample/CRUDToCQRS/07-FlattenedLayers/ECommerce.Domain/Storage/ECommerceDbContext.cs index e0cbc00ea..e1973e74a 100644 --- a/Sample/CRUDToCQRS/07-FlattenedLayers/ECommerce.Domain/Storage/ECommerceDbContext.cs +++ b/Sample/CRUDToCQRS/07-FlattenedLayers/ECommerce.Domain/Storage/ECommerceDbContext.cs @@ -4,14 +4,8 @@ namespace ECommerce.Domain.Storage; -public class ECommerceDbContext: DbContext +public class ECommerceDbContext(DbContextOptions options): DbContext(options) { - public ECommerceDbContext(DbContextOptions options) - : base(options) - { - - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/Sample/CRUDToCQRS/07-FlattenedLayers/ECommerce/Controllers/ProductsController.cs b/Sample/CRUDToCQRS/07-FlattenedLayers/ECommerce/Controllers/ProductsController.cs index bf7baa0ce..4e7a1faee 100644 --- a/Sample/CRUDToCQRS/07-FlattenedLayers/ECommerce/Controllers/ProductsController.cs +++ b/Sample/CRUDToCQRS/07-FlattenedLayers/ECommerce/Controllers/ProductsController.cs @@ -16,13 +16,8 @@ namespace ECommerce.Controllers; [ApiController] [Route("api/[controller]")] -public class ProductsController: Controller +public class ProductsController(ECommerceDbContext dbContext): Controller { - private readonly ECommerceDbContext dbContext; - - public ProductsController(ECommerceDbContext dbContext) => - this.dbContext = dbContext; - [HttpPost] public async Task CreateAsync( [FromBody] CreateProductRequest request, diff --git a/Sample/CRUDToCQRS/07-FlattenedLayers/ECommerce/Controllers/ProductsReadOnlyController.cs b/Sample/CRUDToCQRS/07-FlattenedLayers/ECommerce/Controllers/ProductsReadOnlyController.cs index fea00ebf0..ebfd9140a 100644 --- a/Sample/CRUDToCQRS/07-FlattenedLayers/ECommerce/Controllers/ProductsReadOnlyController.cs +++ b/Sample/CRUDToCQRS/07-FlattenedLayers/ECommerce/Controllers/ProductsReadOnlyController.cs @@ -6,12 +6,8 @@ namespace ECommerce.Controllers; [ApiController] -public class ProductsReadOnlyController: Controller +public class ProductsReadOnlyController(IQueryable products): Controller { - private readonly IQueryable products; - - public ProductsReadOnlyController(IQueryable products) => this.products = products; - [HttpGet("api/products/{id:guid}")] public Task GetById([FromRoute] Guid id, CancellationToken ct) => products.HandleAsync(new GetProductById(id), ct); diff --git a/Sample/CRUDToCQRS/08-SlicedEndpoints/ECommerce.Domain/Storage/ECommerceDbContext.cs b/Sample/CRUDToCQRS/08-SlicedEndpoints/ECommerce.Domain/Storage/ECommerceDbContext.cs index e0cbc00ea..e1973e74a 100644 --- a/Sample/CRUDToCQRS/08-SlicedEndpoints/ECommerce.Domain/Storage/ECommerceDbContext.cs +++ b/Sample/CRUDToCQRS/08-SlicedEndpoints/ECommerce.Domain/Storage/ECommerceDbContext.cs @@ -4,14 +4,8 @@ namespace ECommerce.Domain.Storage; -public class ECommerceDbContext: DbContext +public class ECommerceDbContext(DbContextOptions options): DbContext(options) { - public ECommerceDbContext(DbContextOptions options) - : base(options) - { - - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/Sample/CRUDToCQRS/09-MultipleModules/ECommerce.Domain/Storage/ECommerceDbContext.cs b/Sample/CRUDToCQRS/09-MultipleModules/ECommerce.Domain/Storage/ECommerceDbContext.cs index e0cbc00ea..e1973e74a 100644 --- a/Sample/CRUDToCQRS/09-MultipleModules/ECommerce.Domain/Storage/ECommerceDbContext.cs +++ b/Sample/CRUDToCQRS/09-MultipleModules/ECommerce.Domain/Storage/ECommerceDbContext.cs @@ -4,14 +4,8 @@ namespace ECommerce.Domain.Storage; -public class ECommerceDbContext: DbContext +public class ECommerceDbContext(DbContextOptions options): DbContext(options) { - public ECommerceDbContext(DbContextOptions options) - : base(options) - { - - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/AddingProduct/AddProductTests.cs b/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/AddingProduct/AddProductTests.cs index d1aefd280..93a283baa 100644 --- a/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/AddingProduct/AddProductTests.cs +++ b/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/AddingProduct/AddProductTests.cs @@ -10,18 +10,14 @@ namespace Carts.Api.Tests.ShoppingCarts.AddingProduct; using static ShoppingCartsApi; -public class AddProductTests: IClassFixture> +public class AddProductTests(ApiSpecification api): IClassFixture> { - private readonly ApiSpecification API; - - public AddProductTests(ApiSpecification api) => API = api; - private readonly ProductItemRequest product = new(Guid.NewGuid(), 1); [Fact] [Trait("Category", "Acceptance")] public Task Post_Should_AddProductItem_To_ShoppingCart() => - API + api .Given("Opened Shopping Cart", OpenShoppingCart()) .When( "Add new product", diff --git a/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Canceling/CancelShoppingCartTests.cs b/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Canceling/CancelShoppingCartTests.cs index 5411d0b63..30d6731bb 100644 --- a/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Canceling/CancelShoppingCartTests.cs +++ b/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Canceling/CancelShoppingCartTests.cs @@ -8,17 +8,14 @@ namespace Carts.Api.Tests.ShoppingCarts.Canceling; -public class CancelShoppingCartTests: IClassFixture> +public class CancelShoppingCartTests(ApiSpecification api): IClassFixture> { - private readonly ApiSpecification API; - public CancelShoppingCartTests(ApiSpecification api) => API = api; - public readonly Guid ClientId = Guid.NewGuid(); [Fact] [Trait("Category", "Acceptance")] public Task Delete_Should_Return_OK_And_Cancel_Shopping_Cart() => - API + api .Given(OpenShoppingCart(ClientId)) .When( "Cancel Shopping Cart", diff --git a/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Confirming/ConfirmShoppingCartTests.cs b/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Confirming/ConfirmShoppingCartTests.cs index 3af5a2355..142994b33 100644 --- a/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Confirming/ConfirmShoppingCartTests.cs +++ b/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Confirming/ConfirmShoppingCartTests.cs @@ -10,16 +10,12 @@ namespace Carts.Api.Tests.ShoppingCarts.Confirming; using static ShoppingCartsApi; -public class ConfirmShoppingCartTests: IClassFixture> +public class ConfirmShoppingCartTests(ApiSpecification api): IClassFixture> { - private readonly ApiSpecification API; - - public ConfirmShoppingCartTests(ApiSpecification api) => API = api; - [Fact] [Trait("Category", "Acceptance")] public Task Put_Should_Return_OK_And_Confirm_Shopping_Cart() => - API + api .Given( "Shopping Cart with Product Item", OpenShoppingCart(ClientId), diff --git a/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Opening/OpenShoppingCartTests.cs b/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Opening/OpenShoppingCartTests.cs index 444a7ba6d..d38c30342 100644 --- a/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Opening/OpenShoppingCartTests.cs +++ b/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Opening/OpenShoppingCartTests.cs @@ -8,14 +8,12 @@ namespace Carts.Api.Tests.ShoppingCarts.Opening; -public class OpenShoppingCartTests: IClassFixture> +public class OpenShoppingCartTests(ApiSpecification api): IClassFixture> { - private readonly ApiSpecification API; - [Fact] public Task Post_ShouldReturn_CreatedStatus_With_CartId() => - API.Scenario( - API.Given() + api.Scenario( + api.Given() .When( POST, URI("/api/ShoppingCarts/"), @@ -23,7 +21,7 @@ public class OpenShoppingCartTests: IClassFixture> ) .Then(CREATED_WITH_DEFAULT_HEADERS(eTag: 1)), response => - API.Given() + api.Given() .When(GET, URI($"/api/ShoppingCarts/{response.GetCreatedId()}")) .Until(RESPONSE_ETAG_IS(1)) .Then( @@ -38,7 +36,5 @@ public class OpenShoppingCartTests: IClassFixture> })) ); - public OpenShoppingCartTests(ApiSpecification api) => API = api; - public readonly Guid ClientId = Guid.NewGuid(); } diff --git a/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/RemovingProduct/RemoveProductTests.cs b/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/RemovingProduct/RemoveProductTests.cs index 1134e94b1..54dbcd36c 100644 --- a/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/RemovingProduct/RemoveProductTests.cs +++ b/Sample/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/RemovingProduct/RemoveProductTests.cs @@ -46,32 +46,28 @@ public async Task InitializeAsync() public Task DisposeAsync() => Task.CompletedTask; } -public class RemoveProductTests: IClassFixture +public class RemoveProductTests(RemoveProductFixture api): IClassFixture { - private readonly RemoveProductFixture API; - - public RemoveProductTests(RemoveProductFixture api) => API = api; - [Fact] [Trait("Category", "Acceptance")] public Task Delete_Should_Return_OK_And_Cancel_Shopping_Cart() => - API + api .Given() .When( DELETE, URI( - $"/api/ShoppingCarts/{API.ShoppingCartId}/products/{API.ProductItem.ProductId}?quantity={RemovedCount}&unitPrice={API.UnitPrice.ToString(CultureInfo.InvariantCulture)}"), + $"/api/ShoppingCarts/{api.ShoppingCartId}/products/{api.ProductItem.ProductId}?quantity={RemovedCount}&unitPrice={api.UnitPrice.ToString(CultureInfo.InvariantCulture)}"), HEADERS(IF_MATCH(2)) ) .Then(NO_CONTENT) .And() - .When(GET, URI($"/api/ShoppingCarts/{API.ShoppingCartId}")) + .When(GET, URI($"/api/ShoppingCarts/{api.ShoppingCartId}")) .Until(RESPONSE_ETAG_IS(3)) .Then( OK, RESPONSE_BODY(details => { - details.Id.Should().Be(API.ShoppingCartId); + details.Id.Should().Be(api.ShoppingCartId); details.Status.Should().Be(ShoppingCartStatus.Pending); details.ProductItems.Should().HaveCount(1); var productItem = details.ProductItems.Single(); @@ -79,12 +75,12 @@ public class RemoveProductTests: IClassFixture PricedProductItem.Create( ProductItem.From ( - API.ProductItem.ProductId!.Value, - API.ProductItem.Quantity!.Value - RemovedCount + api.ProductItem.ProductId!.Value, + api.ProductItem.Quantity!.Value - RemovedCount ), - API.UnitPrice + api.UnitPrice )); - details.ClientId.Should().Be(API.ClientId); + details.ClientId.Should().Be(api.ClientId); details.Version.Should().Be(3); })); diff --git a/Sample/ECommerce/Carts/Carts.Api/Controllers/ShoppingCartsController.cs b/Sample/ECommerce/Carts/Carts.Api/Controllers/ShoppingCartsController.cs index 96f5ec6a3..53b4fb957 100644 --- a/Sample/ECommerce/Carts/Carts.Api/Controllers/ShoppingCartsController.cs +++ b/Sample/ECommerce/Carts/Carts.Api/Controllers/ShoppingCartsController.cs @@ -19,22 +19,12 @@ namespace Carts.Api.Controllers; [Route("api/[controller]")] -public class ShoppingCartsController: Controller +public class ShoppingCartsController( + ICommandBus commandBus, + IQueryBus queryBus, + IIdGenerator idGenerator) + : Controller { - private readonly ICommandBus commandBus; - private readonly IQueryBus queryBus; - private readonly IIdGenerator idGenerator; - - public ShoppingCartsController( - ICommandBus commandBus, - IQueryBus queryBus, - IIdGenerator idGenerator) - { - this.commandBus = commandBus; - this.queryBus = queryBus; - this.idGenerator = idGenerator; - } - [HttpPost] public async Task OpenCart([FromBody] OpenShoppingCartRequest? request) { diff --git a/Sample/ECommerce/Carts/Carts/ShoppingCarts/AddingProduct/AddProduct.cs b/Sample/ECommerce/Carts/Carts/ShoppingCarts/AddingProduct/AddProduct.cs index 31925a63b..9b22a2179 100644 --- a/Sample/ECommerce/Carts/Carts/ShoppingCarts/AddingProduct/AddProduct.cs +++ b/Sample/ECommerce/Carts/Carts/ShoppingCarts/AddingProduct/AddProduct.cs @@ -19,21 +19,12 @@ public static AddProduct Create(Guid cartId, ProductItem productItem) } } -internal class HandleAddProduct: - ICommandHandler +internal class HandleAddProduct( + IMartenRepository cartRepository, + IProductPriceCalculator productPriceCalculator) + : + ICommandHandler { - private readonly IMartenRepository cartRepository; - private readonly IProductPriceCalculator productPriceCalculator; - - public HandleAddProduct( - IMartenRepository cartRepository, - IProductPriceCalculator productPriceCalculator - ) - { - this.cartRepository = cartRepository; - this.productPriceCalculator = productPriceCalculator; - } - public Task Handle(AddProduct command, CancellationToken ct) { var (cartId, productItem) = command; diff --git a/Sample/ECommerce/Carts/Carts/ShoppingCarts/CancelingCart/CancelShoppingCart.cs b/Sample/ECommerce/Carts/Carts/ShoppingCarts/CancelingCart/CancelShoppingCart.cs index 6355153e3..46e9457c1 100644 --- a/Sample/ECommerce/Carts/Carts/ShoppingCarts/CancelingCart/CancelShoppingCart.cs +++ b/Sample/ECommerce/Carts/Carts/ShoppingCarts/CancelingCart/CancelShoppingCart.cs @@ -16,14 +16,9 @@ public static CancelShoppingCart Create(Guid cartId) } } -internal class HandleCancelShoppingCart: +internal class HandleCancelShoppingCart(IMartenRepository cartRepository): ICommandHandler { - private readonly IMartenRepository cartRepository; - - public HandleCancelShoppingCart(IMartenRepository cartRepository) => - this.cartRepository = cartRepository; - public Task Handle(CancelShoppingCart command, CancellationToken ct) => cartRepository.GetAndUpdate( command.CartId, diff --git a/Sample/ECommerce/Carts/Carts/ShoppingCarts/ConfirmingCart/ConfirmShoppingCart.cs b/Sample/ECommerce/Carts/Carts/ShoppingCarts/ConfirmingCart/ConfirmShoppingCart.cs index 9d8f5fdc4..6b2313930 100644 --- a/Sample/ECommerce/Carts/Carts/ShoppingCarts/ConfirmingCart/ConfirmShoppingCart.cs +++ b/Sample/ECommerce/Carts/Carts/ShoppingCarts/ConfirmingCart/ConfirmShoppingCart.cs @@ -16,14 +16,9 @@ public static ConfirmShoppingCart Create(Guid cartId) } } -internal class HandleConfirmShoppingCart: +internal class HandleConfirmShoppingCart(IMartenRepository cartRepository): ICommandHandler { - private readonly IMartenRepository cartRepository; - - public HandleConfirmShoppingCart(IMartenRepository cartRepository) => - this.cartRepository = cartRepository; - public Task Handle(ConfirmShoppingCart command, CancellationToken ct) => cartRepository.GetAndUpdate( command.CartId, diff --git a/Sample/ECommerce/Carts/Carts/ShoppingCarts/FinalizingCart/ShoppingCartFinalized.cs b/Sample/ECommerce/Carts/Carts/ShoppingCarts/FinalizingCart/ShoppingCartFinalized.cs index 7b56a7342..0ce8a8c3f 100644 --- a/Sample/ECommerce/Carts/Carts/ShoppingCarts/FinalizingCart/ShoppingCartFinalized.cs +++ b/Sample/ECommerce/Carts/Carts/ShoppingCarts/FinalizingCart/ShoppingCartFinalized.cs @@ -25,20 +25,10 @@ DateTime FinalizedAt } } -internal class HandleCartFinalized: IEventHandler> +internal class HandleCartFinalized( + IQuerySession querySession, + IEventBus eventBus): IEventHandler> { - private readonly IQuerySession querySession; - private readonly IEventBus eventBus; - - public HandleCartFinalized( - IQuerySession querySession, - IEventBus eventBus - ) - { - this.querySession = querySession; - this.eventBus = eventBus; - } - public async Task Handle(EventEnvelope @event, CancellationToken cancellationToken) { var cart = await querySession.LoadAsync(@event.Data.CartId, cancellationToken) diff --git a/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCartAtVersion/GetCartAtVersion.cs b/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCartAtVersion/GetCartAtVersion.cs index 95aed79dc..a2a7ce3c1 100644 --- a/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCartAtVersion/GetCartAtVersion.cs +++ b/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCartAtVersion/GetCartAtVersion.cs @@ -21,14 +21,9 @@ public static GetCartAtVersion Create(Guid? cartId, long? version) } } -internal class HandleGetCartAtVersion : +internal class HandleGetCartAtVersion(IQuerySession querySession): IQueryHandler { - private readonly IQuerySession querySession; - - public HandleGetCartAtVersion(IQuerySession querySession) => - this.querySession = querySession; - public async Task Handle(GetCartAtVersion query, CancellationToken cancellationToken) { var (cartId, version) = query; diff --git a/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCartById/GetCartById.cs b/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCartById/GetCartById.cs index 2b640160f..32483eb81 100644 --- a/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCartById/GetCartById.cs +++ b/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCartById/GetCartById.cs @@ -16,14 +16,9 @@ public static GetCartById Create(Guid cartId) } } -internal class HandleGetCartById: +internal class HandleGetCartById(IQuerySession querySession): IQueryHandler { - private readonly IQuerySession querySession; - - public HandleGetCartById(IQuerySession querySession) => - this.querySession = querySession; - public Task Handle(GetCartById query, CancellationToken cancellationToken) => querySession.LoadAsync(query.CartId, cancellationToken); } diff --git a/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCartHistory/GetCartHistory.cs b/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCartHistory/GetCartHistory.cs index f5ffe6b55..a9408cc68 100644 --- a/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCartHistory/GetCartHistory.cs +++ b/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCartHistory/GetCartHistory.cs @@ -21,14 +21,9 @@ public static GetCartHistory Create(Guid cartId, int pageNumber = 1, int pageSiz } } -internal class HandleGetCartHistory: +internal class HandleGetCartHistory(IQuerySession querySession): IQueryHandler> { - private readonly IQuerySession querySession; - - public HandleGetCartHistory(IQuerySession querySession) => - this.querySession = querySession; - public Task> Handle(GetCartHistory query, CancellationToken cancellationToken) { var (cartId, pageNumber, pageSize) = query; diff --git a/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCarts/GetCarts.cs b/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCarts/GetCarts.cs index da6a6a62a..73056163d 100644 --- a/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCarts/GetCarts.cs +++ b/Sample/ECommerce/Carts/Carts/ShoppingCarts/GettingCarts/GetCarts.cs @@ -20,14 +20,9 @@ public static GetCarts Create(int? pageNumber = 1, int? pageSize = 20) } } -internal class HandleGetCarts: +internal class HandleGetCarts(IQuerySession querySession): IQueryHandler> { - private readonly IQuerySession querySession; - - public HandleGetCarts(IQuerySession querySession) => - this.querySession = querySession; - public Task> Handle(GetCarts query, CancellationToken cancellationToken) { var (pageNumber, pageSize) = query; diff --git a/Sample/ECommerce/Carts/Carts/ShoppingCarts/OpeningCart/OpenShoppingCart.cs b/Sample/ECommerce/Carts/Carts/ShoppingCarts/OpeningCart/OpenShoppingCart.cs index 2d6d34e78..08a672752 100644 --- a/Sample/ECommerce/Carts/Carts/ShoppingCarts/OpeningCart/OpenShoppingCart.cs +++ b/Sample/ECommerce/Carts/Carts/ShoppingCarts/OpeningCart/OpenShoppingCart.cs @@ -19,14 +19,9 @@ public static OpenShoppingCart Create(Guid? cartId, Guid? clientId) } } -internal class HandleOpenShoppingCart: +internal class HandleOpenShoppingCart(IMartenRepository cartRepository): ICommandHandler { - private readonly IMartenRepository cartRepository; - - public HandleOpenShoppingCart(IMartenRepository cartRepository) => - this.cartRepository = cartRepository; - public Task Handle(OpenShoppingCart command, CancellationToken ct) { var (cartId, clientId) = command; diff --git a/Sample/ECommerce/Carts/Carts/ShoppingCarts/RemovingProduct/RemoveProduct.cs b/Sample/ECommerce/Carts/Carts/ShoppingCarts/RemovingProduct/RemoveProduct.cs index 5ae04f542..baa9f5ffc 100644 --- a/Sample/ECommerce/Carts/Carts/ShoppingCarts/RemovingProduct/RemoveProduct.cs +++ b/Sample/ECommerce/Carts/Carts/ShoppingCarts/RemovingProduct/RemoveProduct.cs @@ -18,14 +18,9 @@ public static RemoveProduct Create(Guid cartId, PricedProductItem productItem) } } -internal class HandleRemoveProduct: +internal class HandleRemoveProduct(IMartenRepository cartRepository): ICommandHandler { - private readonly IMartenRepository cartRepository; - - public HandleRemoveProduct(IMartenRepository cartRepository) => - this.cartRepository = cartRepository; - public Task Handle(RemoveProduct command, CancellationToken ct) { var (cartId, productItem) = command; diff --git a/Sample/ECommerce/Orders/Orders.Api.Tests/Orders/InitializingOrder/InitializeOrderTests.cs b/Sample/ECommerce/Orders/Orders.Api.Tests/Orders/InitializingOrder/InitializeOrderTests.cs index 6c2774a3a..d4bde80e9 100644 --- a/Sample/ECommerce/Orders/Orders.Api.Tests/Orders/InitializingOrder/InitializeOrderTests.cs +++ b/Sample/ECommerce/Orders/Orders.Api.Tests/Orders/InitializingOrder/InitializeOrderTests.cs @@ -6,16 +6,11 @@ namespace Orders.Api.Tests.Orders.InitializingOrder; -public class InitializeOrderTests: IClassFixture> +public class InitializeOrderTests(TestWebApplicationFactory fixture) + : IClassFixture> { - private readonly ApiSpecification API; - private readonly TestWebApplicationFactory fixture; - - public InitializeOrderTests(TestWebApplicationFactory fixture) - { - this.fixture = fixture; - API = ApiSpecification.Setup(fixture); - } + private readonly ApiSpecification API = ApiSpecification.Setup(fixture); + private readonly TestWebApplicationFactory fixture = fixture; [Fact] [Trait("Category", "Acceptance")] diff --git a/Sample/ECommerce/Orders/Orders.Api/Controllers/CartsController.cs b/Sample/ECommerce/Orders/Orders.Api/Controllers/CartsController.cs index 3a4d716aa..80f06f6d6 100644 --- a/Sample/ECommerce/Orders/Orders.Api/Controllers/CartsController.cs +++ b/Sample/ECommerce/Orders/Orders.Api/Controllers/CartsController.cs @@ -10,21 +10,13 @@ namespace Orders.Api.Controllers; [Route("api/[controller]")] -public class OrdersController: Controller +public class OrdersController( + ICommandBus commandBus, + IQueryBus queryBus, + IIdGenerator idGenerator) + : Controller { - private readonly ICommandBus commandBus; - private readonly IQueryBus queryBus; - private readonly IIdGenerator idGenerator; - - public OrdersController( - ICommandBus commandBus, - IQueryBus queryBus, - IIdGenerator idGenerator) - { - this.commandBus = commandBus; - this.queryBus = queryBus; - this.idGenerator = idGenerator; - } + private readonly IQueryBus queryBus = queryBus; [HttpPost] public async Task InitOrder([FromBody] InitOrderRequest? request) diff --git a/Sample/ECommerce/Orders/Orders/Orders/CancellingOrder/CancelOrder.cs b/Sample/ECommerce/Orders/Orders/Orders/CancellingOrder/CancelOrder.cs index 07442fcae..96e074aa1 100644 --- a/Sample/ECommerce/Orders/Orders/Orders/CancellingOrder/CancelOrder.cs +++ b/Sample/ECommerce/Orders/Orders/Orders/CancellingOrder/CancelOrder.cs @@ -20,14 +20,9 @@ public static CancelOrder Create(Guid? orderId, OrderCancellationReason? cancell } } -public class HandleCancelOrder: +public class HandleCancelOrder(IMartenRepository orderRepository): ICommandHandler { - private readonly IMartenRepository orderRepository; - - public HandleCancelOrder(IMartenRepository orderRepository) => - this.orderRepository = orderRepository; - public Task Handle(CancelOrder command, CancellationToken ct) => orderRepository.GetAndUpdate( command.OrderId, diff --git a/Sample/ECommerce/Orders/Orders/Orders/CompletingOrder/CompleteOrder.cs b/Sample/ECommerce/Orders/Orders/Orders/CompletingOrder/CompleteOrder.cs index 3d7428d5e..2012e5d78 100644 --- a/Sample/ECommerce/Orders/Orders/Orders/CompletingOrder/CompleteOrder.cs +++ b/Sample/ECommerce/Orders/Orders/Orders/CompletingOrder/CompleteOrder.cs @@ -16,14 +16,9 @@ public static CompleteOrder Create(Guid? orderId) } } -public class HandleCompleteOrder: +public class HandleCompleteOrder(IMartenRepository orderRepository): ICommandHandler { - private readonly IMartenRepository orderRepository; - - public HandleCompleteOrder(IMartenRepository orderRepository) => - this.orderRepository = orderRepository; - public Task Handle(CompleteOrder command, CancellationToken ct) => orderRepository.GetAndUpdate( command.OrderId, diff --git a/Sample/ECommerce/Orders/Orders/Orders/InitializingOrder/InitializeOrder.cs b/Sample/ECommerce/Orders/Orders/Orders/InitializingOrder/InitializeOrder.cs index 3daf11a15..1e64e19f1 100644 --- a/Sample/ECommerce/Orders/Orders/Orders/InitializingOrder/InitializeOrder.cs +++ b/Sample/ECommerce/Orders/Orders/Orders/InitializingOrder/InitializeOrder.cs @@ -31,14 +31,9 @@ decimal TotalPrice } } -public class HandleInitializeOrder: +public class HandleInitializeOrder(IMartenRepository orderRepository): ICommandHandler { - private readonly IMartenRepository orderRepository; - - public HandleInitializeOrder(IMartenRepository orderRepository) => - this.orderRepository = orderRepository; - public Task Handle(InitializeOrder command, CancellationToken ct) { var (orderId, clientId, productItems, totalPrice) = command; diff --git a/Sample/ECommerce/Orders/Orders/Orders/OrderSaga.cs b/Sample/ECommerce/Orders/Orders/Orders/OrderSaga.cs index cfbc93a50..19cf88b5e 100644 --- a/Sample/ECommerce/Orders/Orders/Orders/OrderSaga.cs +++ b/Sample/ECommerce/Orders/Orders/Orders/OrderSaga.cs @@ -15,7 +15,7 @@ namespace Orders.Orders; -public class OrderSaga: +public class OrderSaga(IIdGenerator idGenerator, ICommandBus commandBus): IEventHandler, IEventHandler, IEventHandler, @@ -24,15 +24,6 @@ public class OrderSaga: IEventHandler, IEventHandler { - private readonly IIdGenerator idGenerator; - private readonly ICommandBus commandBus; - - public OrderSaga(IIdGenerator idGenerator, ICommandBus commandBus) - { - this.idGenerator = idGenerator; - this.commandBus = commandBus; - } - // Happy path public async Task Handle(CartFinalized @event, CancellationToken ct) { diff --git a/Sample/ECommerce/Orders/Orders/Orders/RecordingOrderPayment/RecordOrderPayment.cs b/Sample/ECommerce/Orders/Orders/Orders/RecordingOrderPayment/RecordOrderPayment.cs index 39f31a921..c2fb1f5e6 100644 --- a/Sample/ECommerce/Orders/Orders/Orders/RecordingOrderPayment/RecordOrderPayment.cs +++ b/Sample/ECommerce/Orders/Orders/Orders/RecordingOrderPayment/RecordOrderPayment.cs @@ -22,14 +22,9 @@ public static RecordOrderPayment Create(Guid? orderId, Guid? paymentId, DateTime } } -public class HandleRecordOrderPayment: +public class HandleRecordOrderPayment(IMartenRepository orderRepository): ICommandHandler { - private readonly IMartenRepository orderRepository; - - public HandleRecordOrderPayment(IMartenRepository orderRepository) => - this.orderRepository = orderRepository; - public Task Handle(RecordOrderPayment command, CancellationToken ct) { var (orderId, paymentId, recordedAt) = command; diff --git a/Sample/ECommerce/Orders/Orders/Payments/DiscardingPayment/DiscardPayment.cs b/Sample/ECommerce/Orders/Orders/Payments/DiscardingPayment/DiscardPayment.cs index e37f56a4f..91a3d450c 100644 --- a/Sample/ECommerce/Orders/Orders/Payments/DiscardingPayment/DiscardPayment.cs +++ b/Sample/ECommerce/Orders/Orders/Payments/DiscardingPayment/DiscardPayment.cs @@ -17,19 +17,12 @@ public static DiscardPayment Create(Guid paymentId) } } -public class HandleDiscardPayment: - ICommandHandler +public class HandleDiscardPayment( + ExternalServicesConfig externalServicesConfig, + IExternalCommandBus externalCommandBus) + : + ICommandHandler { - private readonly ExternalServicesConfig externalServicesConfig; - private readonly IExternalCommandBus externalCommandBus; - - public HandleDiscardPayment(ExternalServicesConfig externalServicesConfig, - IExternalCommandBus externalCommandBus) - { - this.externalServicesConfig = externalServicesConfig; - this.externalCommandBus = externalCommandBus; - } - public async Task Handle(DiscardPayment command, CancellationToken ct) { await externalCommandBus.Delete( diff --git a/Sample/ECommerce/Orders/Orders/Payments/RequestingPayment/RequestPayment.cs b/Sample/ECommerce/Orders/Orders/Payments/RequestingPayment/RequestPayment.cs index dc9fc353a..7ac06f351 100644 --- a/Sample/ECommerce/Orders/Orders/Payments/RequestingPayment/RequestPayment.cs +++ b/Sample/ECommerce/Orders/Orders/Payments/RequestingPayment/RequestPayment.cs @@ -19,19 +19,12 @@ public static RequestPayment Create(Guid orderId, decimal amount) } } -public class HandleRequestPayment: - ICommandHandler +public class HandleRequestPayment( + ExternalServicesConfig externalServicesConfig, + IExternalCommandBus externalCommandBus) + : + ICommandHandler { - private readonly ExternalServicesConfig externalServicesConfig; - private readonly IExternalCommandBus externalCommandBus; - - public HandleRequestPayment(ExternalServicesConfig externalServicesConfig, - IExternalCommandBus externalCommandBus) - { - this.externalServicesConfig = externalServicesConfig; - this.externalCommandBus = externalCommandBus; - } - public async Task Handle(RequestPayment command, CancellationToken ct) { await externalCommandBus.Post( diff --git a/Sample/ECommerce/Orders/Orders/Products/ProductItem.cs b/Sample/ECommerce/Orders/Orders/Products/ProductItem.cs index 3254035bd..8e697d86e 100644 --- a/Sample/ECommerce/Orders/Orders/Products/ProductItem.cs +++ b/Sample/ECommerce/Orders/Orders/Products/ProductItem.cs @@ -1,14 +1,8 @@ namespace Orders.Products; -public class ProductItem +public class ProductItem(Guid productId, int quantity) { - public Guid ProductId { get; } + public Guid ProductId { get; } = productId; - public int Quantity { get; } - - public ProductItem(Guid productId, int quantity) - { - ProductId = productId; - Quantity = quantity; - } -} \ No newline at end of file + public int Quantity { get; } = quantity; +} diff --git a/Sample/ECommerce/Orders/Orders/Shipments/SendingPackage/SendPackage.cs b/Sample/ECommerce/Orders/Orders/Shipments/SendingPackage/SendPackage.cs index fd1bf1acf..a9d320b38 100644 --- a/Sample/ECommerce/Orders/Orders/Shipments/SendingPackage/SendPackage.cs +++ b/Sample/ECommerce/Orders/Orders/Shipments/SendingPackage/SendPackage.cs @@ -23,18 +23,10 @@ IReadOnlyList productItems } } -public class HandleSendPackage: - ICommandHandler +public class HandleSendPackage(ExternalServicesConfig externalServicesConfig, IExternalCommandBus externalCommandBus) + : + ICommandHandler { - private readonly ExternalServicesConfig externalServicesConfig; - private readonly IExternalCommandBus externalCommandBus; - - public HandleSendPackage(ExternalServicesConfig externalServicesConfig, IExternalCommandBus externalCommandBus) - { - this.externalServicesConfig = externalServicesConfig; - this.externalCommandBus = externalCommandBus; - } - public async Task Handle(SendPackage command, CancellationToken ct) { await externalCommandBus.Post( diff --git a/Sample/ECommerce/Payments/Payments.Api.Tests/Payments/RequestingPayment/RequestPaymentsTests.cs b/Sample/ECommerce/Payments/Payments.Api.Tests/Payments/RequestingPayment/RequestPaymentsTests.cs index 15272b48c..805228b96 100644 --- a/Sample/ECommerce/Payments/Payments.Api.Tests/Payments/RequestingPayment/RequestPaymentsTests.cs +++ b/Sample/ECommerce/Payments/Payments.Api.Tests/Payments/RequestingPayment/RequestPaymentsTests.cs @@ -6,16 +6,11 @@ namespace Payments.Api.Tests.Payments.RequestingPayment; -public class RequestPaymentsTests: IClassFixture> +public class RequestPaymentsTests(TestWebApplicationFactory fixture) + : IClassFixture> { - private readonly ApiSpecification API; - private readonly TestWebApplicationFactory fixture; - - public RequestPaymentsTests(TestWebApplicationFactory fixture) - { - this.fixture = fixture; - API = ApiSpecification.Setup(fixture); - } + private readonly ApiSpecification API = ApiSpecification.Setup(fixture); + private readonly TestWebApplicationFactory fixture = fixture; [Fact] [Trait("Category", "Acceptance")] diff --git a/Sample/ECommerce/Payments/Payments.Api/Controllers/PaymentsController.cs b/Sample/ECommerce/Payments/Payments.Api/Controllers/PaymentsController.cs index 2a91761ad..fb70b5e4c 100644 --- a/Sample/ECommerce/Payments/Payments.Api/Controllers/PaymentsController.cs +++ b/Sample/ECommerce/Payments/Payments.Api/Controllers/PaymentsController.cs @@ -8,21 +8,13 @@ namespace Payments.Api.Controllers; [Route("api/[controller]")] -public class PaymentsController: Controller +public class PaymentsController( + ICommandBus commandBus, + IQueryBus queryBus, + IIdGenerator idGenerator) + : Controller { - private readonly ICommandBus commandBus; - private readonly IQueryBus queryBus; - private readonly IIdGenerator idGenerator; - - public PaymentsController( - ICommandBus commandBus, - IQueryBus queryBus, - IIdGenerator idGenerator) - { - this.commandBus = commandBus; - this.queryBus = queryBus; - this.idGenerator = idGenerator; - } + private readonly IQueryBus queryBus = queryBus; [HttpPost] public async Task RequestPayment([FromBody] RequestPaymentRequest? request) diff --git a/Sample/ECommerce/Payments/Payments/Payments/CompletingPayment/CompletePayment.cs b/Sample/ECommerce/Payments/Payments/Payments/CompletingPayment/CompletePayment.cs index 83b71a6ce..8f15ccf33 100644 --- a/Sample/ECommerce/Payments/Payments/Payments/CompletingPayment/CompletePayment.cs +++ b/Sample/ECommerce/Payments/Payments/Payments/CompletingPayment/CompletePayment.cs @@ -17,14 +17,9 @@ public static CompletePayment Create(Guid? paymentId) } } -public class HandleCompletePayment: +public class HandleCompletePayment(IMartenRepository paymentRepository): ICommandHandler { - private readonly IMartenRepository paymentRepository; - - public HandleCompletePayment(IMartenRepository paymentRepository) => - this.paymentRepository = paymentRepository; - public async Task Handle(CompletePayment command, CancellationToken ct) { var paymentId = command.PaymentId; diff --git a/Sample/ECommerce/Payments/Payments/Payments/DiscardingPayment/DiscardPayment.cs b/Sample/ECommerce/Payments/Payments/Payments/DiscardingPayment/DiscardPayment.cs index 0e4e9415b..dfdbb9afb 100644 --- a/Sample/ECommerce/Payments/Payments/Payments/DiscardingPayment/DiscardPayment.cs +++ b/Sample/ECommerce/Payments/Payments/Payments/DiscardingPayment/DiscardPayment.cs @@ -19,14 +19,9 @@ public static DiscardPayment Create(Guid? paymentId, DiscardReason? discardReaso } } -public class HandleDiscardPayment: +public class HandleDiscardPayment(IMartenRepository paymentRepository): ICommandHandler { - private readonly IMartenRepository paymentRepository; - - public HandleDiscardPayment(IMartenRepository paymentRepository) => - this.paymentRepository = paymentRepository; - public Task Handle(DiscardPayment command, CancellationToken ct) { var (paymentId, _) = command; diff --git a/Sample/ECommerce/Payments/Payments/Payments/FailingPayment/PaymentFailed.cs b/Sample/ECommerce/Payments/Payments/Payments/FailingPayment/PaymentFailed.cs index 10a83e9a0..18d660ef2 100644 --- a/Sample/ECommerce/Payments/Payments/Payments/FailingPayment/PaymentFailed.cs +++ b/Sample/ECommerce/Payments/Payments/Payments/FailingPayment/PaymentFailed.cs @@ -23,22 +23,12 @@ PaymentFailReason failReason } -public class TransformIntoPaymentFailed : +public class TransformIntoPaymentFailed( + IEventBus eventBus, + IQuerySession querySession): IEventHandler>, IEventHandler> { - private readonly IEventBus eventBus; - private readonly IQuerySession querySession; - - public TransformIntoPaymentFailed( - IEventBus eventBus, - IQuerySession querySession - ) - { - this.eventBus = eventBus; - this.querySession = querySession; - } - public async Task Handle(EventEnvelope @event, CancellationToken cancellationToken) { var payment = await querySession.LoadAsync(@event.Data.PaymentId, cancellationToken); diff --git a/Sample/ECommerce/Payments/Payments/Payments/FinalizingPayment/PaymentFinalized.cs b/Sample/ECommerce/Payments/Payments/Payments/FinalizingPayment/PaymentFinalized.cs index 1adf77240..dcba0b77d 100644 --- a/Sample/ECommerce/Payments/Payments/Payments/FinalizingPayment/PaymentFinalized.cs +++ b/Sample/ECommerce/Payments/Payments/Payments/FinalizingPayment/PaymentFinalized.cs @@ -26,21 +26,11 @@ public static PaymentFinalized Create(Guid paymentId, Guid orderId, decimal amou } } -public class TransformIntoPaymentFinalized: +public class TransformIntoPaymentFinalized( + IEventBus eventBus, + IQuerySession querySession): IEventHandler> { - private readonly IEventBus eventBus; - private readonly IQuerySession querySession; - - public TransformIntoPaymentFinalized( - IEventBus eventBus, - IQuerySession querySession - ) - { - this.eventBus = eventBus; - this.querySession = querySession; - } - public async Task Handle(EventEnvelope @event, CancellationToken cancellationToken) { var (paymentId, completedAt) = @event.Data; diff --git a/Sample/ECommerce/Payments/Payments/Payments/RequestingPayment/RequestPayment.cs b/Sample/ECommerce/Payments/Payments/Payments/RequestingPayment/RequestPayment.cs index dd6027e05..491d322a4 100644 --- a/Sample/ECommerce/Payments/Payments/Payments/RequestingPayment/RequestPayment.cs +++ b/Sample/ECommerce/Payments/Payments/Payments/RequestingPayment/RequestPayment.cs @@ -26,14 +26,9 @@ decimal Amount } } -public class HandleRequestPayment: +public class HandleRequestPayment(IMartenRepository paymentRepository): ICommandHandler { - private readonly IMartenRepository paymentRepository; - - public HandleRequestPayment(IMartenRepository paymentRepository) => - this.paymentRepository = paymentRepository; - public Task Handle(RequestPayment command, CancellationToken ct) { var (paymentId, orderId, amount) = command; diff --git a/Sample/ECommerce/Payments/Payments/Payments/TimingOutPayment/TimeOutPayment.cs b/Sample/ECommerce/Payments/Payments/Payments/TimingOutPayment/TimeOutPayment.cs index ae6e6e4b1..f14de4ad1 100644 --- a/Sample/ECommerce/Payments/Payments/Payments/TimingOutPayment/TimeOutPayment.cs +++ b/Sample/ECommerce/Payments/Payments/Payments/TimingOutPayment/TimeOutPayment.cs @@ -19,14 +19,9 @@ public static TimeOutPayment Create(Guid? paymentId, DateTime? timedOutAt) } } -public class HandleTimeOutPayment: +public class HandleTimeOutPayment(IMartenRepository paymentRepository): ICommandHandler { - private readonly IMartenRepository paymentRepository; - - public HandleTimeOutPayment(IMartenRepository paymentRepository) => - this.paymentRepository = paymentRepository; - public Task Handle(TimeOutPayment command, CancellationToken ct) { var (paymentId, _) = command; diff --git a/Sample/ECommerce/Shipments/Shipments.Api.Tests/Packages/SendPackageTests.cs b/Sample/ECommerce/Shipments/Shipments.Api.Tests/Packages/SendPackageTests.cs index 99c29de5b..834d20bba 100644 --- a/Sample/ECommerce/Shipments/Shipments.Api.Tests/Packages/SendPackageTests.cs +++ b/Sample/ECommerce/Shipments/Shipments.Api.Tests/Packages/SendPackageTests.cs @@ -8,16 +8,10 @@ namespace Shipments.Api.Tests.Packages; -public class SendPackageTests: IClassFixture> +public class SendPackageTests(TestWebApplicationFactory fixture) + : IClassFixture> { - private readonly ApiSpecification API; - private readonly TestWebApplicationFactory fixture; - - public SendPackageTests(TestWebApplicationFactory fixture) - { - this.fixture = fixture; - API = ApiSpecification.Setup(fixture); - } + private readonly ApiSpecification API = ApiSpecification.Setup(fixture); [Fact] [Trait("Category", "Acceptance")] diff --git a/Sample/ECommerce/Shipments/Shipments.Api/Controllers/ShipmentsController.cs b/Sample/ECommerce/Shipments/Shipments.Api/Controllers/ShipmentsController.cs index 0c2712e34..5f371b4f5 100644 --- a/Sample/ECommerce/Shipments/Shipments.Api/Controllers/ShipmentsController.cs +++ b/Sample/ECommerce/Shipments/Shipments.Api/Controllers/ShipmentsController.cs @@ -5,14 +5,9 @@ namespace Shipments.Api.Controllers; [Route("api/[controller]")] -public class ShipmentsController: Controller +public class ShipmentsController(IPackageService packageService): Controller { - private readonly IPackageService packageService; - - public ShipmentsController(IPackageService packageService) - { - this.packageService = packageService ?? throw new ArgumentNullException(nameof(packageService)); - } + private readonly IPackageService packageService = packageService ?? throw new ArgumentNullException(nameof(packageService)); [HttpPost] public async Task Send([FromBody] SendPackage? request) diff --git a/Sample/ECommerce/Shipments/Shipments/Packages/Events/External/PackageWasSent.cs b/Sample/ECommerce/Shipments/Shipments/Packages/Events/External/PackageWasSent.cs index c03368f88..e97419423 100644 --- a/Sample/ECommerce/Shipments/Shipments/Packages/Events/External/PackageWasSent.cs +++ b/Sample/ECommerce/Shipments/Shipments/Packages/Events/External/PackageWasSent.cs @@ -3,21 +3,14 @@ namespace Shipments.Packages.Events.External; -internal class PackageWasSent : IExternalEvent +internal class PackageWasSent(Guid packageId, Guid orderId, IReadOnlyList productItems, DateTime sentAt) + : IExternalEvent { - public Guid PackageId { get; } - public Guid OrderId { get; } + public Guid PackageId { get; } = packageId; + public Guid OrderId { get; } = orderId; - public IReadOnlyList ProductItems { get; } + public IReadOnlyList ProductItems { get; } = productItems; - public DateTime SentAt { get; } - - public PackageWasSent(Guid packageId, Guid orderId, IReadOnlyList productItems, DateTime sentAt) - { - OrderId = orderId; - ProductItems = productItems; - SentAt = sentAt; - PackageId = packageId; - } -} \ No newline at end of file + public DateTime SentAt { get; } = sentAt; +} diff --git a/Sample/ECommerce/Shipments/Shipments/Packages/Events/External/ProductWasOutOfStock.cs b/Sample/ECommerce/Shipments/Shipments/Packages/Events/External/ProductWasOutOfStock.cs index 7e8891825..6720dbddd 100644 --- a/Sample/ECommerce/Shipments/Shipments/Packages/Events/External/ProductWasOutOfStock.cs +++ b/Sample/ECommerce/Shipments/Shipments/Packages/Events/External/ProductWasOutOfStock.cs @@ -2,16 +2,9 @@ namespace Shipments.Packages.Events.External; -internal class ProductWasOutOfStock: IExternalEvent +internal class ProductWasOutOfStock(Guid orderId, DateTime availabilityCheckedAt): IExternalEvent { - public Guid OrderId { get; } + public Guid OrderId { get; } = orderId; - public DateTime AvailabilityCheckedAt { get; } - - - public ProductWasOutOfStock(Guid orderId, DateTime availabilityCheckedAt) - { - OrderId = orderId; - AvailabilityCheckedAt = availabilityCheckedAt; - } -} \ No newline at end of file + public DateTime AvailabilityCheckedAt { get; } = availabilityCheckedAt; +} diff --git a/Sample/ECommerce/Shipments/Shipments/Packages/PackageService.cs b/Sample/ECommerce/Shipments/Shipments/Packages/PackageService.cs index 9d6c13f29..551e34369 100644 --- a/Sample/ECommerce/Shipments/Shipments/Packages/PackageService.cs +++ b/Sample/ECommerce/Shipments/Shipments/Packages/PackageService.cs @@ -14,26 +14,19 @@ public interface IPackageService Task GetById(Guid id, CancellationToken ct); } -internal class PackageService: IPackageService +internal class PackageService( + ShipmentsDbContext dbContext, + IEventBus eventBus, + IProductAvailabilityService productAvailabilityService) + : IPackageService { - private readonly ShipmentsDbContext dbContext; - private readonly IEventBus eventBus; - private readonly IProductAvailabilityService productAvailabilityService; + private readonly ShipmentsDbContext dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); + private readonly IEventBus eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus)); + private readonly IProductAvailabilityService productAvailabilityService = productAvailabilityService ?? + throw new ArgumentNullException(nameof(productAvailabilityService)); private DbSet Packages => dbContext.Packages; - public PackageService( - ShipmentsDbContext dbContext, - IEventBus eventBus, - IProductAvailabilityService productAvailabilityService - ) - { - this.dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); - this.eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus)); - this.productAvailabilityService = productAvailabilityService ?? - throw new ArgumentNullException(nameof(productAvailabilityService)); - } - public async Task GetById(Guid id, CancellationToken ct) { var package = await dbContext.Packages diff --git a/Sample/ECommerce/Shipments/Shipments/Storage/ShipmentsDbContext.cs b/Sample/ECommerce/Shipments/Shipments/Storage/ShipmentsDbContext.cs index 37fd104b3..c8a0941aa 100644 --- a/Sample/ECommerce/Shipments/Shipments/Storage/ShipmentsDbContext.cs +++ b/Sample/ECommerce/Shipments/Shipments/Storage/ShipmentsDbContext.cs @@ -3,12 +3,7 @@ namespace Shipments.Storage; -internal class ShipmentsDbContext: DbContext +internal class ShipmentsDbContext(DbContextOptions options): DbContext(options) { - public ShipmentsDbContext(DbContextOptions options) - : base(options) - { - } - public DbSet Packages { get; set; } = default!; -} \ No newline at end of file +} diff --git a/Sample/EventPipelines/EventPipelines.MediatR/MediatorEventRouter.cs b/Sample/EventPipelines/EventPipelines.MediatR/MediatorEventRouter.cs index 4c71e0c04..cb63ced26 100644 --- a/Sample/EventPipelines/EventPipelines.MediatR/MediatorEventRouter.cs +++ b/Sample/EventPipelines/EventPipelines.MediatR/MediatorEventRouter.cs @@ -2,17 +2,11 @@ namespace EventPipelines.MediatR; -public class MediatorEventRouter : INotificationHandler where T : INotification +public class MediatorEventRouter(IEventBus eventBus): INotificationHandler + where T : INotification { - private readonly IEventBus eventBus; - - public MediatorEventRouter(IEventBus eventBus) - { - this.eventBus = eventBus; - } - public async Task Handle(T notification, CancellationToken cancellationToken) { await eventBus.Publish(notification, cancellationToken); } -} \ No newline at end of file +} diff --git a/Sample/EventPipelines/EventPipelines.Tests/ClassesWithBuilderTest.cs b/Sample/EventPipelines/EventPipelines.Tests/ClassesWithBuilderTest.cs index fe399974a..f3653f744 100644 --- a/Sample/EventPipelines/EventPipelines.Tests/ClassesWithBuilderTest.cs +++ b/Sample/EventPipelines/EventPipelines.Tests/ClassesWithBuilderTest.cs @@ -42,15 +42,8 @@ public class ToAdminAdded: IEventTransformation ValueTask.FromResult(new AdminAdded(@event.FirstName, @event.LastName)); } - public class HandleAdminAdded: IEventHandler + public class HandleAdminAdded(AdminStorage adminStorage): IEventHandler { - private readonly AdminStorage adminStorage; - - public HandleAdminAdded(AdminStorage adminStorage) - { - this.adminStorage = adminStorage; - } - public ValueTask Handle(AdminAdded @event, CancellationToken ct) { adminStorage.GlobalAdmins.Add(@event); @@ -68,15 +61,8 @@ public class SendToTenants: IEventTransformation + public class HandleAdminGrantedInTenant(AdminStorage adminStorage): IEventHandler { - private readonly AdminStorage adminStorage; - - public HandleAdminGrantedInTenant(AdminStorage adminStorage) - { - this.adminStorage = adminStorage; - } - public ValueTask Handle(AdminGrantedInTenant @event, CancellationToken ct) { adminStorage.AdminsInTenants.Add(@event); diff --git a/Sample/EventPipelines/EventPipelines.Tests/ClassesWithIoCTest.cs b/Sample/EventPipelines/EventPipelines.Tests/ClassesWithIoCTest.cs index 86479f1e4..8e30d85b9 100644 --- a/Sample/EventPipelines/EventPipelines.Tests/ClassesWithIoCTest.cs +++ b/Sample/EventPipelines/EventPipelines.Tests/ClassesWithIoCTest.cs @@ -45,15 +45,8 @@ public class ToAdminAdded: IEventTransformation ValueTask.FromResult(new AdminAdded(@event.FirstName, @event.LastName)); } - public class HandleAdminAdded: IEventHandler + public class HandleAdminAdded(AdminStorage adminStorage): IEventHandler { - private readonly AdminStorage adminStorage; - - public HandleAdminAdded(AdminStorage adminStorage) - { - this.adminStorage = adminStorage; - } - public ValueTask Handle(AdminAdded @event, CancellationToken ct) { adminStorage.GlobalAdmins.Add(@event); @@ -71,15 +64,8 @@ public class SendToTenants: IEventTransformation + public class HandleAdminGrantedInTenant(AdminStorage adminStorage): IEventHandler { - private readonly AdminStorage adminStorage; - - public HandleAdminGrantedInTenant(AdminStorage adminStorage) - { - this.adminStorage = adminStorage; - } - public ValueTask Handle(AdminGrantedInTenant @event, CancellationToken ct) { adminStorage.AdminsInTenants.Add(@event); diff --git a/Sample/EventPipelines/EventPipelines.Tests/ClassesWithMediatRTest.cs b/Sample/EventPipelines/EventPipelines.Tests/ClassesWithMediatRTest.cs index f7620e718..46d7e050e 100644 --- a/Sample/EventPipelines/EventPipelines.Tests/ClassesWithMediatRTest.cs +++ b/Sample/EventPipelines/EventPipelines.Tests/ClassesWithMediatRTest.cs @@ -45,15 +45,8 @@ public class ToAdminAdded: IEventTransformation ValueTask.FromResult(new AdminAdded(@event.FirstName, @event.LastName)); } - public class HandleAdminAdded: IEventHandler + public class HandleAdminAdded(AdminStorage adminStorage): IEventHandler { - private readonly AdminStorage adminStorage; - - public HandleAdminAdded(AdminStorage adminStorage) - { - this.adminStorage = adminStorage; - } - public ValueTask Handle(AdminAdded @event, CancellationToken ct) { adminStorage.GlobalAdmins.Add(@event); @@ -71,15 +64,8 @@ public class SendToTenants: IEventTransformation + public class HandleAdminGrantedInTenant(AdminStorage adminStorage): IEventHandler { - private readonly AdminStorage adminStorage; - - public HandleAdminGrantedInTenant(AdminStorage adminStorage) - { - this.adminStorage = adminStorage; - } - public ValueTask Handle(AdminGrantedInTenant @event, CancellationToken ct) { adminStorage.AdminsInTenants.Add(@event); diff --git a/Sample/EventPipelines/EventPipelines.Tests/PureFunctionsWithBuilderTest.cs b/Sample/EventPipelines/EventPipelines.Tests/PureFunctionsWithBuilderTest.cs index a6789d264..e040118b8 100644 --- a/Sample/EventPipelines/EventPipelines.Tests/PureFunctionsWithBuilderTest.cs +++ b/Sample/EventPipelines/EventPipelines.Tests/PureFunctionsWithBuilderTest.cs @@ -49,18 +49,13 @@ public static class AdminPipeline AdminsInTenants.Add(@event); } - private readonly EventHandlersBuilder builder; - - public PureFunctionsWithBuilderTest() - { - builder = EventHandlersBuilder - .Setup() - .Filter(AdminPipeline.IsAdmin) - .Transform(AdminPipeline.ToAdminAdded) - .Handle(AdminPipeline.Handle) - .Transform>(AdminPipeline.SendToTenants) - .Handle(AdminPipeline.Handle); - } + private readonly EventHandlersBuilder builder = EventHandlersBuilder + .Setup() + .Filter(AdminPipeline.IsAdmin) + .Transform(AdminPipeline.ToAdminAdded) + .Handle(AdminPipeline.Handle) + .Transform>(AdminPipeline.SendToTenants) + .Handle(AdminPipeline.Handle); [Fact] public async Task ShouldWork() @@ -77,4 +72,4 @@ public async Task ShouldWork() AdminPipeline.GlobalAdmins.Single().FirstName.Should().Be("Big"); AdminPipeline.GlobalAdmins.Single().LastName.Should().Be("Bird"); } -} \ No newline at end of file +} diff --git a/Sample/EventStoreDB/DataAnalytics/MarketBasketAnalytics.Api/Startup.cs b/Sample/EventStoreDB/DataAnalytics/MarketBasketAnalytics.Api/Startup.cs index 67c1ccaa3..ea579e527 100644 --- a/Sample/EventStoreDB/DataAnalytics/MarketBasketAnalytics.Api/Startup.cs +++ b/Sample/EventStoreDB/DataAnalytics/MarketBasketAnalytics.Api/Startup.cs @@ -6,14 +6,9 @@ namespace MarketBasketAnalytics.Api { - public class Startup + public class Startup(IConfiguration configuration) { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } = configuration; // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/AddingProduct/AddProductTests.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/AddingProduct/AddProductTests.cs index 89a2caabf..c0daab8f7 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/AddingProduct/AddProductTests.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/AddingProduct/AddProductTests.cs @@ -10,19 +10,15 @@ namespace Carts.Api.Tests.ShoppingCarts.AddingProduct; using static ShoppingCartsApi; -public class AddProductTests: IClassFixture> +public class AddProductTests(ApiSpecification api): IClassFixture> { - private readonly ApiSpecification API; - - public AddProductTests(ApiSpecification api) => API = api; - [Fact] [Trait("Category", "Acceptance")] public async Task Post_Should_AddProductItem_To_ShoppingCart() { var product = new ProductItemRequest(Guid.NewGuid(), 1); - await API + await api .Given("Opened Shopping Cart", OpenShoppingCart()) .When( "Add new product", diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Canceling/CancelShoppingCartTests.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Canceling/CancelShoppingCartTests.cs index 42f260163..a77acab7a 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Canceling/CancelShoppingCartTests.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Canceling/CancelShoppingCartTests.cs @@ -8,17 +8,14 @@ namespace Carts.Api.Tests.ShoppingCarts.Canceling; -public class CancelShoppingCartTests: IClassFixture> +public class CancelShoppingCartTests(ApiSpecification api): IClassFixture> { - private readonly ApiSpecification API; - public CancelShoppingCartTests(ApiSpecification api) => API = api; - public readonly Guid ClientId = Guid.NewGuid(); [Fact] [Trait("Category", "Acceptance")] public Task Delete_Should_Return_OK_And_Cancel_Shopping_Cart() => - API + api .Given("Opened Shopping Cart", OpenShoppingCart(ClientId)) .When( "Cancel Shopping Cart", diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Confirming/ConfirmShoppingCartTests.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Confirming/ConfirmShoppingCartTests.cs index 80aa8a6b9..c54e0531f 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Confirming/ConfirmShoppingCartTests.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Confirming/ConfirmShoppingCartTests.cs @@ -25,38 +25,33 @@ public async Task InitializeAsync() public Task DisposeAsync() => Task.CompletedTask; } -public class ConfirmShoppingCartTests: IClassFixture +public class ConfirmShoppingCartTests(ConfirmShoppingCartFixture api): IClassFixture { - - private readonly ConfirmShoppingCartFixture API; - - public ConfirmShoppingCartTests(ConfirmShoppingCartFixture api) => API = api; - [Fact] [Trait("Category", "Acceptance")] public async Task Put_Should_Return_OK_And_Cancel_Shopping_Cart() { - await API + await api .Given() .When( PUT, - URI($"/api/ShoppingCarts/{API.ShoppingCartId}/confirmation"), + URI($"/api/ShoppingCarts/{api.ShoppingCartId}/confirmation"), HEADERS(IF_MATCH(0)) ) .Then(OK); - await API + await api .Given() - .When(GET, URI($"/api/ShoppingCarts/{API.ShoppingCartId}")) + .When(GET, URI($"/api/ShoppingCarts/{api.ShoppingCartId}")) .Until(RESPONSE_ETAG_IS(1)) .Then( OK, RESPONSE_BODY(details => { - details.Id.Should().Be(API.ShoppingCartId); + details.Id.Should().Be(api.ShoppingCartId); details.Status.Should().Be(ShoppingCartStatus.Confirmed); details.ProductItems.Should().BeEmpty(); - details.ClientId.Should().Be(API.ClientId); + details.ClientId.Should().Be(api.ClientId); details.Version.Should().Be(1); })); diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Opening/OpenShoppingCartTests.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Opening/OpenShoppingCartTests.cs index e2a0cfb5a..e94b335bb 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Opening/OpenShoppingCartTests.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/Opening/OpenShoppingCartTests.cs @@ -8,14 +8,12 @@ namespace Carts.Api.Tests.ShoppingCarts.Opening; -public class OpenShoppingCartTests: IClassFixture> +public class OpenShoppingCartTests(ApiSpecification api): IClassFixture> { - private readonly ApiSpecification API; - [Fact] public Task Post_ShouldReturn_CreatedStatus_With_CartId() => - API.Scenario( - API.Given() + api.Scenario( + api.Given() .When( POST, URI("/api/ShoppingCarts/"), @@ -23,7 +21,7 @@ public class OpenShoppingCartTests: IClassFixture> ) .Then(CREATED_WITH_DEFAULT_HEADERS(eTag: 0)), response => - API.Given() + api.Given() .When(GET, URI($"/api/ShoppingCarts/{response.GetCreatedId()}")) .Until(RESPONSE_ETAG_IS(0)) .Then( @@ -38,7 +36,5 @@ public class OpenShoppingCartTests: IClassFixture> })) ); - public OpenShoppingCartTests(ApiSpecification api) => API = api; - public readonly Guid ClientId = Guid.NewGuid(); } diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/RemovingProduct/RemoveProductTests.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/RemovingProduct/RemoveProductTests.cs index 26d7b8b74..fdd1eb986 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/RemovingProduct/RemoveProductTests.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts.Api.Tests/ShoppingCarts/RemovingProduct/RemoveProductTests.cs @@ -46,33 +46,29 @@ public async Task InitializeAsync() public Task DisposeAsync() => Task.CompletedTask; } -public class RemoveProductTests: IClassFixture +public class RemoveProductTests(RemoveProductFixture api): IClassFixture { - private readonly RemoveProductFixture API; - - public RemoveProductTests(RemoveProductFixture api) => API = api; - [Fact] [Trait("Category", "Acceptance")] public async Task Delete_Should_Return_OK_And_Cancel_Shopping_Cart() { - await API + await api .Given() .When( DELETE, URI( - $"/api/ShoppingCarts/{API.ShoppingCartId}/products/{API.ProductItem.ProductId}?quantity={RemovedCount}&unitPrice={API.UnitPrice.ToString(CultureInfo.InvariantCulture)}"), + $"/api/ShoppingCarts/{api.ShoppingCartId}/products/{api.ProductItem.ProductId}?quantity={RemovedCount}&unitPrice={api.UnitPrice.ToString(CultureInfo.InvariantCulture)}"), HEADERS(IF_MATCH(1)) ) .Then(NO_CONTENT) .And() - .When(GET, URI($"/api/ShoppingCarts/{API.ShoppingCartId}")) + .When(GET, URI($"/api/ShoppingCarts/{api.ShoppingCartId}")) .Until(RESPONSE_ETAG_IS(2)) .Then( OK, RESPONSE_BODY(details => { - details.Id.Should().Be(API.ShoppingCartId); + details.Id.Should().Be(api.ShoppingCartId); details.Status.Should().Be(ShoppingCartStatus.Pending); details.ProductItems.Should().HaveCount(1); var productItem = details.ProductItems.Single(); @@ -80,12 +76,12 @@ await API new PricedProductItem( new ProductItem ( - API.ProductItem.ProductId!.Value, - API.ProductItem.Quantity!.Value - RemovedCount + api.ProductItem.ProductId!.Value, + api.ProductItem.Quantity!.Value - RemovedCount ), - API.UnitPrice + api.UnitPrice )); - details.ClientId.Should().Be(API.ClientId); + details.ClientId.Should().Be(api.ClientId); details.Version.Should().Be(2); })); } diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts.Api/Controllers/ShoppingCartsController.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts.Api/Controllers/ShoppingCartsController.cs index c720d6fa6..30eb45b36 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts.Api/Controllers/ShoppingCartsController.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts.Api/Controllers/ShoppingCartsController.cs @@ -19,22 +19,12 @@ namespace Carts.Api.Controllers; [Route("api/[controller]")] -public class ShoppingCartsController: Controller +public class ShoppingCartsController( + ICommandBus commandBus, + IQueryBus queryBus, + IIdGenerator idGenerator) + : Controller { - private readonly ICommandBus commandBus; - private readonly IQueryBus queryBus; - private readonly IIdGenerator idGenerator; - - public ShoppingCartsController( - ICommandBus commandBus, - IQueryBus queryBus, - IIdGenerator idGenerator) - { - this.commandBus = commandBus; - this.queryBus = queryBus; - this.idGenerator = idGenerator; - } - [HttpPost] public async Task OpenCart([FromBody] OpenShoppingCartRequest? request) { diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/AddingProduct/AddProduct.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/AddingProduct/AddProduct.cs index 1ede5dafc..139926642 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/AddingProduct/AddProduct.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/AddingProduct/AddProduct.cs @@ -21,21 +21,12 @@ public static AddProduct Create(Guid? cartId, ProductItem? productItem) } } -internal class HandleAddProduct: - ICommandHandler +internal class HandleAddProduct( + IEventStoreDBRepository cartRepository, + IProductPriceCalculator productPriceCalculator) + : + ICommandHandler { - private readonly IEventStoreDBRepository cartRepository; - private readonly IProductPriceCalculator productPriceCalculator; - - public HandleAddProduct( - IEventStoreDBRepository cartRepository, - IProductPriceCalculator productPriceCalculator - ) - { - this.cartRepository = cartRepository; - this.productPriceCalculator = productPriceCalculator; - } - public Task Handle(AddProduct command, CancellationToken ct) { var (cartId, productItem) = command; diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/CancelingCart/CancelShoppingCart.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/CancelingCart/CancelShoppingCart.cs index cbbee0fa9..f060cf633 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/CancelingCart/CancelShoppingCart.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/CancelingCart/CancelShoppingCart.cs @@ -16,14 +16,9 @@ public static CancelShoppingCart Create(Guid? cartId) } } -internal class HandleCancelCart: +internal class HandleCancelCart(IEventStoreDBRepository cartRepository): ICommandHandler { - private readonly IEventStoreDBRepository cartRepository; - - public HandleCancelCart(IEventStoreDBRepository cartRepository) => - this.cartRepository = cartRepository; - public Task Handle(CancelShoppingCart command, CancellationToken ct) => cartRepository.GetAndUpdate( command.CartId, diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/ConfirmingCart/ConfirmShoppingCart.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/ConfirmingCart/ConfirmShoppingCart.cs index f6a007499..dee4cf07f 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/ConfirmingCart/ConfirmShoppingCart.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/ConfirmingCart/ConfirmShoppingCart.cs @@ -16,14 +16,9 @@ public static ConfirmShoppingCart Create(Guid? cartId) } } -internal class HandleConfirmCart: +internal class HandleConfirmCart(IEventStoreDBRepository cartRepository): ICommandHandler { - private readonly IEventStoreDBRepository cartRepository; - - public HandleConfirmCart(IEventStoreDBRepository cartRepository) => - this.cartRepository = cartRepository; - public Task Handle(ConfirmShoppingCart command, CancellationToken ct) => cartRepository.GetAndUpdate( command.CartId, diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/FinalizingCart/ShoppingCartFinalized.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/FinalizingCart/ShoppingCartFinalized.cs index 11d3a4096..29feb0ebc 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/FinalizingCart/ShoppingCartFinalized.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/FinalizingCart/ShoppingCartFinalized.cs @@ -25,20 +25,10 @@ DateTime FinalizedAt } } -internal class HandleCartFinalized: IEventHandler> +internal class HandleCartFinalized( + IQuerySession querySession, + IEventBus eventBus): IEventHandler> { - private readonly IQuerySession querySession; - private readonly IEventBus eventBus; - - public HandleCartFinalized( - IQuerySession querySession, - IEventBus eventBus - ) - { - this.querySession = querySession; - this.eventBus = eventBus; - } - public async Task Handle(EventEnvelope @event, CancellationToken cancellationToken) { var cart = await querySession.LoadAsync(@event.Data.CartId, cancellationToken) diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCartAtVersion/GetCartAtVersion.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCartAtVersion/GetCartAtVersion.cs index 7450fbc99..cd6b0a5f4 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCartAtVersion/GetCartAtVersion.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCartAtVersion/GetCartAtVersion.cs @@ -22,16 +22,9 @@ public static GetCartAtVersion Create(Guid? cartId, ulong? version) } } -internal class HandleGetCartAtVersion: +internal class HandleGetCartAtVersion(EventStoreClient eventStore): IQueryHandler { - private readonly EventStoreClient eventStore; - - public HandleGetCartAtVersion(EventStoreClient eventStore) - { - this.eventStore = eventStore; - } - public async Task Handle(GetCartAtVersion request, CancellationToken cancellationToken) { var cart = await eventStore.AggregateStream( diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCartById/GetCartById.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCartById/GetCartById.cs index be1dd2877..c5b091a16 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCartById/GetCartById.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCartById/GetCartById.cs @@ -17,14 +17,9 @@ public static GetCartById Create(Guid? cartId) } } -internal class HandleGetCartById : +internal class HandleGetCartById(IQuerySession querySession): IQueryHandler { - private readonly IQuerySession querySession; - - public HandleGetCartById(IQuerySession querySession) => - this.querySession = querySession; - public async Task Handle(GetCartById request, CancellationToken cancellationToken) { var cart = await querySession.LoadAsync(request.CartId, cancellationToken); diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCartHistory/GetCartHistory.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCartHistory/GetCartHistory.cs index b2829dd37..ea9de247e 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCartHistory/GetCartHistory.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCartHistory/GetCartHistory.cs @@ -23,14 +23,9 @@ public static GetCartHistory Create(Guid? cartId, int? pageNumber = 1, int? page } } -internal class HandleGetCartHistory: +internal class HandleGetCartHistory(IQuerySession querySession): IQueryHandler> { - private readonly IQuerySession querySession; - - public HandleGetCartHistory(IQuerySession querySession) => - this.querySession = querySession; - public Task> Handle(GetCartHistory query, CancellationToken cancellationToken) { var (cartId, pageNumber, pageSize) = query; diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCarts/GetCarts.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCarts/GetCarts.cs index 17afdbe75..e1e72b600 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCarts/GetCarts.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/GettingCarts/GetCarts.cs @@ -20,14 +20,9 @@ public static GetCarts Create(int? pageNumber = 1, int? pageSize = 20) } } -internal class HandleGetCarts: +internal class HandleGetCarts(IQuerySession querySession): IQueryHandler> { - private readonly IQuerySession querySession; - - public HandleGetCarts(IQuerySession querySession) => - this.querySession = querySession; - public Task> Handle(GetCarts request, CancellationToken cancellationToken) { var (pageNumber, pageSize) = request; diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/OpeningCart/OpenShoppingCart.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/OpeningCart/OpenShoppingCart.cs index a4df2a0b5..33c787a18 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/OpeningCart/OpenShoppingCart.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/OpeningCart/OpenShoppingCart.cs @@ -19,14 +19,9 @@ public static OpenShoppingCart Create(Guid? cartId, Guid? clientId) } } -internal class HandleOpenCart: +internal class HandleOpenCart(IEventStoreDBRepository cartRepository): ICommandHandler { - private readonly IEventStoreDBRepository cartRepository; - - public HandleOpenCart(IEventStoreDBRepository cartRepository) => - this.cartRepository = cartRepository; - public Task Handle(OpenShoppingCart command, CancellationToken ct) { var (cartId, clientId) = command; diff --git a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/RemovingProduct/RemoveProduct.cs b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/RemovingProduct/RemoveProduct.cs index 1780c596c..d5e7925e7 100644 --- a/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/RemovingProduct/RemoveProduct.cs +++ b/Sample/EventStoreDB/ECommerce/Carts/Carts/ShoppingCarts/RemovingProduct/RemoveProduct.cs @@ -20,14 +20,9 @@ public static RemoveProduct Create(Guid? cartId, PricedProductItem? productItem) } } -internal class HandleRemoveProduct: +internal class HandleRemoveProduct(IEventStoreDBRepository cartRepository): ICommandHandler { - private readonly IEventStoreDBRepository cartRepository; - - public HandleRemoveProduct(IEventStoreDBRepository cartRepository) => - this.cartRepository = cartRepository; - public Task Handle(RemoveProduct command, CancellationToken ct) { var (cartId, pricedProductItem) = command; diff --git a/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/AddingProduct/AddProductTests.cs b/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/AddingProduct/AddProductTests.cs index ddb6d85af..21ef0d8cc 100644 --- a/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/AddingProduct/AddProductTests.cs +++ b/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/AddingProduct/AddProductTests.cs @@ -10,19 +10,15 @@ namespace ECommerce.Api.Tests.ShoppingCarts.AddingProduct; using static ShoppingCartsApi; -public class AddProductTests: IClassFixture> +public class AddProductTests(ApiSpecification api): IClassFixture> { - private readonly ApiSpecification API; - - public AddProductTests(ApiSpecification api) => API = api; - [Fact] [Trait("Category", "Acceptance")] public Task Post_Should_AddProductItem_To_ShoppingCart() { var product = new ProductItemRequest(Guid.NewGuid(), 1); - return API + return api .Given("Opened Shopping Cart", OpenShoppingCart()) .When( "Add new product", diff --git a/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/Canceling/CancelShoppingCartTests.cs b/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/Canceling/CancelShoppingCartTests.cs index adde433e8..fcf79e163 100644 --- a/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/Canceling/CancelShoppingCartTests.cs +++ b/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/Canceling/CancelShoppingCartTests.cs @@ -8,17 +8,14 @@ namespace ECommerce.Api.Tests.ShoppingCarts.Canceling; -public class CancelShoppingCartTests: IClassFixture> +public class CancelShoppingCartTests(ApiSpecification api): IClassFixture> { - private readonly ApiSpecification API; - public CancelShoppingCartTests(ApiSpecification api) => API = api; - public readonly Guid ClientId = Guid.NewGuid(); [Fact] [Trait("Category", "Acceptance")] public Task Delete_Should_Return_OK_And_Cancel_Shopping_Cart() => - API + api .Given("Opened Shopping Cart", OpenShoppingCart(ClientId)) .When( "Cancel Shopping Cart", diff --git a/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/Confirming/ConfirmShoppingCartTests.cs b/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/Confirming/ConfirmShoppingCartTests.cs index 14d4fa729..76d4f85f0 100644 --- a/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/Confirming/ConfirmShoppingCartTests.cs +++ b/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/Confirming/ConfirmShoppingCartTests.cs @@ -8,10 +8,9 @@ namespace ECommerce.Api.Tests.ShoppingCarts.Confirming; -public class ConfirmShoppingCartFixture: ApiSpecification, IAsyncLifetime +public class ConfirmShoppingCartFixture() + : ApiSpecification(new ShoppingCartsApplicationFactory()), IAsyncLifetime { - public ConfirmShoppingCartFixture(): base(new ShoppingCartsApplicationFactory()) { } - public Guid ShoppingCartId { get; private set; } public readonly Guid ClientId = Guid.NewGuid(); @@ -27,35 +26,30 @@ public async Task InitializeAsync() public Task DisposeAsync() => Task.CompletedTask; } -public class ConfirmShoppingCartTests: IClassFixture +public class ConfirmShoppingCartTests(ConfirmShoppingCartFixture api): IClassFixture { - - private readonly ConfirmShoppingCartFixture API; - - public ConfirmShoppingCartTests(ConfirmShoppingCartFixture api) => API = api; - [Fact] [Trait("Category", "Acceptance")] public async Task Put_Should_Return_OK_And_Confirm_Shopping_Cart() { - await API + await api .Given() .When( PUT, - URI($"/api/ShoppingCarts/{API.ShoppingCartId}/confirmation"), + URI($"/api/ShoppingCarts/{api.ShoppingCartId}/confirmation"), HEADERS(IF_MATCH(0)) ) .Then(OK) - .AndWhen(GET, URI($"/api/ShoppingCarts/{API.ShoppingCartId}")) + .AndWhen(GET, URI($"/api/ShoppingCarts/{api.ShoppingCartId}")) .Until(RESPONSE_ETAG_IS(1), maxNumberOfRetries: 10) .Then( OK, RESPONSE_BODY(details => { - details.Id.Should().Be(API.ShoppingCartId); + details.Id.Should().Be(api.ShoppingCartId); details.Status.Should().Be(ShoppingCartStatus.Confirmed); details.ProductItems.Should().BeEmpty(); - details.ClientId.Should().Be(API.ClientId); + details.ClientId.Should().Be(api.ClientId); details.Version.Should().Be(1); })); diff --git a/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/Opening/OpenShoppingCartTests.cs b/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/Opening/OpenShoppingCartTests.cs index 846c33e73..0aaf6beae 100644 --- a/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/Opening/OpenShoppingCartTests.cs +++ b/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/Opening/OpenShoppingCartTests.cs @@ -8,9 +8,10 @@ namespace ECommerce.Api.Tests.ShoppingCarts.Opening; -public class OpenShoppingCartTests: IClassFixture +public class OpenShoppingCartTests(ShoppingCartsApplicationFactory applicationFactory) + : IClassFixture { - private readonly ApiSpecification API; + private readonly ApiSpecification API = ApiSpecification.Setup(applicationFactory); [Fact] public Task Post_ShouldReturn_CreatedStatus_With_CartId() => @@ -38,8 +39,5 @@ public class OpenShoppingCartTests: IClassFixture - API = ApiSpecification.Setup(applicationFactory); - public readonly Guid ClientId = Guid.NewGuid(); } diff --git a/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/RemovingProduct/RemoveProductTests.cs b/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/RemovingProduct/RemoveProductTests.cs index fb0ddbee5..9fe6932fc 100644 --- a/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/RemovingProduct/RemoveProductTests.cs +++ b/Sample/EventStoreDB/Simple/ECommerce.Api.Tests/ShoppingCarts/RemovingProduct/RemoveProductTests.cs @@ -9,9 +9,8 @@ namespace ECommerce.Api.Tests.ShoppingCarts.RemovingProduct; -public class RemoveProductFixture: ApiSpecification, IAsyncLifetime +public class RemoveProductFixture(): ApiSpecification(new ShoppingCartsApplicationFactory()), IAsyncLifetime { - public RemoveProductFixture(): base(new ShoppingCartsApplicationFactory()) { } public Guid ShoppingCartId { get; private set; } public readonly Guid ClientId = Guid.NewGuid(); @@ -46,44 +45,40 @@ public async Task InitializeAsync() public Task DisposeAsync() => Task.CompletedTask; } -public class RemoveProductTests: IClassFixture +public class RemoveProductTests(RemoveProductFixture api): IClassFixture { - private readonly RemoveProductFixture API; - - public RemoveProductTests(RemoveProductFixture api) => API = api; - [Fact] [Trait("Category", "Acceptance")] public async Task Delete_Should_Return_OK_And_Cancel_Shopping_Cart() { - await API + await api .Given() .When( DELETE, URI( - $"/api/ShoppingCarts/{API.ShoppingCartId}/products/{API.ProductItem.ProductId}?quantity={RemovedCount}&unitPrice={API.UnitPrice.ToString(CultureInfo.InvariantCulture)}"), + $"/api/ShoppingCarts/{api.ShoppingCartId}/products/{api.ProductItem.ProductId}?quantity={RemovedCount}&unitPrice={api.UnitPrice.ToString(CultureInfo.InvariantCulture)}"), HEADERS(IF_MATCH(1)) ) .Then(NO_CONTENT) .And() - .When(GET, URI($"/api/ShoppingCarts/{API.ShoppingCartId}")) + .When(GET, URI($"/api/ShoppingCarts/{api.ShoppingCartId}")) .Until(RESPONSE_ETAG_IS(2), maxNumberOfRetries: 10) .Then( OK, RESPONSE_BODY(details => { - details.Id.Should().Be(API.ShoppingCartId); + details.Id.Should().Be(api.ShoppingCartId); details.Status.Should().Be(ShoppingCartStatus.Pending); details.ProductItems.Should().HaveCount(1); var productItem = details.ProductItems.Single(); productItem.Should().BeEquivalentTo( new ShoppingCartDetailsProductItem { - ProductId = API.ProductItem.ProductId!.Value, - Quantity = API.ProductItem.Quantity!.Value - RemovedCount, - UnitPrice = API.UnitPrice + ProductId = api.ProductItem.ProductId!.Value, + Quantity = api.ProductItem.Quantity!.Value - RemovedCount, + UnitPrice = api.UnitPrice }); - details.ClientId.Should().Be(API.ClientId); + details.ClientId.Should().Be(api.ClientId); details.Version.Should().Be(2); })); } diff --git a/Sample/EventStoreDB/Simple/ECommerce.Core/Commands/CommandHandler.cs b/Sample/EventStoreDB/Simple/ECommerce.Core/Commands/CommandHandler.cs index e46e1996f..8d4a4a7fb 100644 --- a/Sample/EventStoreDB/Simple/ECommerce.Core/Commands/CommandHandler.cs +++ b/Sample/EventStoreDB/Simple/ECommerce.Core/Commands/CommandHandler.cs @@ -128,23 +128,13 @@ Action> setup return services; } - public class CommandHandlersBuilder + public class CommandHandlersBuilder( + IServiceCollection services, + Func getDefault, + Func when) where TEntity : class { - public readonly IServiceCollection services; - private readonly Func getDefault; - private readonly Func when; - - public CommandHandlersBuilder( - IServiceCollection services, - Func getDefault, - Func when - ) - { - this.services = services; - this.getDefault = getDefault; - this.when = when; - } + public readonly IServiceCollection services = services; public CommandHandlersBuilder AddOn( Func handle, diff --git a/Sample/EventStoreDB/Simple/ECommerce.Core/Projections/EntityFrameworkProjection.cs b/Sample/EventStoreDB/Simple/ECommerce.Core/Projections/EntityFrameworkProjection.cs index 5547459cf..805f7bb69 100644 --- a/Sample/EventStoreDB/Simple/ECommerce.Core/Projections/EntityFrameworkProjection.cs +++ b/Sample/EventStoreDB/Simple/ECommerce.Core/Projections/EntityFrameworkProjection.cs @@ -20,16 +20,11 @@ public static class EntityFrameworkProjection } } -public class EntityFrameworkProjectionBuilder +public class EntityFrameworkProjectionBuilder(IServiceCollection services) where TView : class where TDbContext : DbContext { - public readonly IServiceCollection services; - - public EntityFrameworkProjectionBuilder(IServiceCollection services) - { - this.services = services; - } + public readonly IServiceCollection services = services; public EntityFrameworkProjectionBuilder AddOn(Func, TView> handler) where TEvent : notnull { @@ -76,23 +71,14 @@ public EntityFrameworkProjectionBuilder(IServiceCollection services) } } -public class AddProjection: IEventHandler> - where TView: class - where TDbContext: DbContext +public class AddProjection( + TDbContext dbContext, + Func, TView> create) + : IEventHandler> + where TView : class + where TDbContext : DbContext where TEvent : notnull { - private readonly TDbContext dbContext; - private readonly Func, TView> create; - - public AddProjection( - TDbContext dbContext, - Func, TView> create - ) - { - this.dbContext = dbContext; - this.create = create; - } - public async Task Handle(EventEnvelope eventEnvelope, CancellationToken ct) { var view = create(eventEnvelope); @@ -102,28 +88,16 @@ public async Task Handle(EventEnvelope eventEnvelope, CancellationToken } } -public class UpdateProjection: IEventHandler> - where TView: class - where TDbContext: DbContext +public class UpdateProjection( + TDbContext dbContext, + Func getViewId, + Action, TView> update, + Func, CancellationToken, Task>? prepare = null) + : IEventHandler> + where TView : class + where TDbContext : DbContext where TEvent : notnull { - private readonly TDbContext dbContext; - private readonly Func getViewId; - private readonly Action, TView> update; - private readonly Func, CancellationToken, Task>? prepare; - - public UpdateProjection( - TDbContext dbContext, - Func getViewId, - Action, TView> update, - Func, CancellationToken, Task>? prepare = null) - { - this.dbContext = dbContext; - this.getViewId = getViewId; - this.update = update; - this.prepare = prepare; - } - public async Task Handle(EventEnvelope eventEnvelope, CancellationToken ct) { var viewId = getViewId(eventEnvelope.Data); diff --git a/Sample/EventStoreDB/Simple/ECommerce/ShoppingCarts/ProductItems/ProductItemsList.cs b/Sample/EventStoreDB/Simple/ECommerce/ShoppingCarts/ProductItems/ProductItemsList.cs index a2c454e4f..83b3d0db0 100644 --- a/Sample/EventStoreDB/Simple/ECommerce/ShoppingCarts/ProductItems/ProductItemsList.cs +++ b/Sample/EventStoreDB/Simple/ECommerce/ShoppingCarts/ProductItems/ProductItemsList.cs @@ -1,14 +1,7 @@ namespace ECommerce.ShoppingCarts.ProductItems; -public class ProductItemsList +public class ProductItemsList(List items) { - private readonly List items; - - public ProductItemsList(List items) - { - this.items = items; - } - public ProductItemsList Add(PricedProductItem productItem) { var clone = new List(items); diff --git a/Sample/EventStoreDB/Simple/ECommerce/Storage/ECommerceDbContext.cs b/Sample/EventStoreDB/Simple/ECommerce/Storage/ECommerceDbContext.cs index f2325fea6..0d3a88838 100644 --- a/Sample/EventStoreDB/Simple/ECommerce/Storage/ECommerceDbContext.cs +++ b/Sample/EventStoreDB/Simple/ECommerce/Storage/ECommerceDbContext.cs @@ -4,14 +4,8 @@ namespace ECommerce.Storage; -public class ECommerceDbContext: DbContext +public class ECommerceDbContext(DbContextOptions options): DbContext(options) { - public ECommerceDbContext(DbContextOptions options) - : base(options) - { - - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.SetupShoppingCartsReadModels(); @@ -32,4 +26,4 @@ public ECommerceDbContext CreateDbContext(params string[] args) return new ECommerceDbContext(optionsBuilder.Options); } -} \ No newline at end of file +} diff --git a/Sample/EventsVersioning/EventsVersioning.Tests/ExplicitSerialization/ShoppingCart.cs b/Sample/EventsVersioning/EventsVersioning.Tests/ExplicitSerialization/ShoppingCart.cs index 7c1a9c41a..aab375a52 100644 --- a/Sample/EventsVersioning/EventsVersioning.Tests/ExplicitSerialization/ShoppingCart.cs +++ b/Sample/EventsVersioning/EventsVersioning.Tests/ExplicitSerialization/ShoppingCart.cs @@ -5,11 +5,10 @@ namespace EventsVersioning.Tests.ExplicitSerialization; using static ShoppingCartEvent; -public abstract class StronglyTypedValue: IEquatable> where T : notnull +public abstract class StronglyTypedValue(T value): IEquatable> + where T : notnull { - public T Value { get; } - - protected StronglyTypedValue(T value) => Value = value; + public T Value { get; } = value; public override string ToString() => Value.ToString()!; @@ -157,10 +156,8 @@ public record Money( Currency Currency ); -public class Price: StronglyTypedValue +public class Price(Money value): StronglyTypedValue(value) { - public Price(Money value): base(value) { } - public static Price Parse(Money value) { if (!value.Amount.IsPositive) diff --git a/Sample/EventsVersioning/EventsVersioning.Tests/SimpleMappings/RenamedProperty.cs b/Sample/EventsVersioning/EventsVersioning.Tests/SimpleMappings/RenamedProperty.cs index 21e95ca51..81cdd630d 100644 --- a/Sample/EventsVersioning/EventsVersioning.Tests/SimpleMappings/RenamedProperty.cs +++ b/Sample/EventsVersioning/EventsVersioning.Tests/SimpleMappings/RenamedProperty.cs @@ -8,20 +8,14 @@ namespace EventsVersioning.Tests.SimpleMappings; public class RenamedProperty { - public class ShoppingCartOpened + public class ShoppingCartOpened( + Guid cartId, + Guid clientId) { [JsonPropertyName("ShoppingCartId")] - public Guid CartId { get; init; } - public Guid ClientId { get; init; } - - public ShoppingCartOpened( - Guid cartId, - Guid clientId - ) - { - CartId = cartId; - ClientId = clientId; - } + public Guid CartId { get; init; } = cartId; + + public Guid ClientId { get; init; } = clientId; } [Fact] diff --git a/Sample/EventsVersioning/EventsVersioning.Tests/Transformations/MultipleTransformationsWithDifferentEventTypes.cs b/Sample/EventsVersioning/EventsVersioning.Tests/Transformations/MultipleTransformationsWithDifferentEventTypes.cs index c0f888862..f5268feb9 100644 --- a/Sample/EventsVersioning/EventsVersioning.Tests/Transformations/MultipleTransformationsWithDifferentEventTypes.cs +++ b/Sample/EventsVersioning/EventsVersioning.Tests/Transformations/MultipleTransformationsWithDifferentEventTypes.cs @@ -115,17 +115,8 @@ public EventTypeMapping Register(params string[] typeNames) public Type Map(string eventType) => mappings[eventType]; } - public class EventSerializer + public class EventSerializer(EventTypeMapping mapping, EventTransformations transformations) { - private readonly EventTypeMapping mapping; - private readonly EventTransformations transformations; - - public EventSerializer(EventTypeMapping mapping, EventTransformations transformations) - { - this.mapping = mapping; - this.transformations = transformations; - } - public object? Deserialize(string eventTypeName, string json) => transformations.TryTransform(eventTypeName, json, out var transformed) ? transformed diff --git a/Sample/EventsVersioning/EventsVersioning.Tests/Transformations/StreamTransformations.cs b/Sample/EventsVersioning/EventsVersioning.Tests/Transformations/StreamTransformations.cs index 2920e03e3..c9cb0a44d 100644 --- a/Sample/EventsVersioning/EventsVersioning.Tests/Transformations/StreamTransformations.cs +++ b/Sample/EventsVersioning/EventsVersioning.Tests/Transformations/StreamTransformations.cs @@ -175,20 +175,11 @@ public EventTypeMapping Register(params string[] typeNames) public Type Map(string eventType) => mappings[eventType]; } - public class EventSerializer + public class EventSerializer( + EventTypeMapping mapping, + StreamTransformations streamTransformations, + EventTransformations transformations) { - private readonly EventTypeMapping mapping; - private readonly StreamTransformations streamTransformations; - private readonly EventTransformations transformations; - - public EventSerializer(EventTypeMapping mapping, StreamTransformations streamTransformations, - EventTransformations transformations) - { - this.mapping = mapping; - this.transformations = transformations; - this.streamTransformations = streamTransformations; - } - public object? Deserialize(string eventTypeName, string json) => transformations.TryTransform(eventTypeName, json, out var transformed) ? transformed diff --git a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/AcknowledgeResolutionIncidentTests.cs b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/AcknowledgeResolutionIncidentTests.cs index b3653122a..24ee3c405 100644 --- a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/AcknowledgeResolutionIncidentTests.cs +++ b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/AcknowledgeResolutionIncidentTests.cs @@ -5,35 +5,31 @@ namespace Helpdesk.Api.Tests.Incidents; -public class AcknowledgeResolutionIncidentTests: IClassFixture +public class AcknowledgeResolutionIncidentTests(ApiWithResolvedIncident api): IClassFixture { [Fact] [Trait("Category", "Acceptance")] public Task ResolveCommand_Succeeds() => - API + api .Given() .When( POST, - URI($"/api/customers/{API.Incident.CustomerId}/incidents/{API.Incident.Id}/acknowledge"), + URI($"/api/customers/{api.Incident.CustomerId}/incidents/{api.Incident.Id}/acknowledge"), HEADERS(IF_MATCH(2)) ) .Then(OK) .And() - .When(GET, URI($"/api/incidents/{API.Incident.Id}")) + .When(GET, URI($"/api/incidents/{api.Incident.Id}")) .Then( OK, RESPONSE_BODY( - API.Incident with + api.Incident with { Status = IncidentStatus.ResolutionAcknowledgedByCustomer, Version = 3 } ) ); - - private readonly ApiWithResolvedIncident API; - - public AcknowledgeResolutionIncidentTests(ApiWithResolvedIncident api) => API = api; } diff --git a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/AssignAgentTests.cs b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/AssignAgentTests.cs index 1449cb101..3ebb22633 100644 --- a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/AssignAgentTests.cs +++ b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/AssignAgentTests.cs @@ -4,32 +4,29 @@ namespace Helpdesk.Api.Tests.Incidents; -public class AssignAgentToIncidentTests: IClassFixture +public class AssignAgentToIncidentTests(ApiWithLoggedIncident api): IClassFixture { [Fact] [Trait("Category", "Acceptance")] public async Task AssignAgentCommand_ChangesIncidentCategory() { - await API + await api .Given() .When( POST, - URI($"/api/agents/{agentId}/incidents/{API.Incident.Id}/assign"), + URI($"/api/agents/{agentId}/incidents/{api.Incident.Id}/assign"), HEADERS(IF_MATCH(1)) ) .Then(OK) .And() - .When(GET, URI($"/api/incidents/{API.Incident.Id}")) + .When(GET, URI($"/api/incidents/{api.Incident.Id}")) .Then( OK, RESPONSE_BODY( - API.Incident with { AgentId = agentId, Version = 2 } + api.Incident with { AgentId = agentId, Version = 2 } ) ); } private readonly Guid agentId = Guid.NewGuid(); - private readonly ApiWithLoggedIncident API; - - public AssignAgentToIncidentTests(ApiWithLoggedIncident api) => API = api; } diff --git a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/CategoriseIncidentTests.cs b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/CategoriseIncidentTests.cs index 72d59c4a2..7c738bc27 100644 --- a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/CategoriseIncidentTests.cs +++ b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/CategoriseIncidentTests.cs @@ -6,36 +6,33 @@ namespace Helpdesk.Api.Tests.Incidents; -public class CategoriseIncidentTests: IClassFixture +public class CategoriseIncidentTests(ApiWithLoggedIncident api): IClassFixture { [Fact] [Trait("Category", "Acceptance")] public async Task CategoriseCommand_ChangesIncidentCategory() { - await API + await api .Given() .When( POST, - URI($"/api/agents/{agentId}/incidents/{API.Incident.Id}/category"), + URI($"/api/agents/{agentId}/incidents/{api.Incident.Id}/category"), BODY(new CategoriseIncidentRequest(category)), HEADERS(IF_MATCH(1)) ) .Then(OK); - await API + await api .Given() - .When(GET, URI($"/api/incidents/{API.Incident.Id}")) + .When(GET, URI($"/api/incidents/{api.Incident.Id}")) .Then( OK, RESPONSE_BODY( - API.Incident with { Category = category, Version = 2 } + api.Incident with { Category = category, Version = 2 } ) ); } private readonly Guid agentId = Guid.NewGuid(); private readonly IncidentCategory category = new Faker().PickRandom(); - private readonly ApiWithLoggedIncident API; - - public CategoriseIncidentTests(ApiWithLoggedIncident api) => API = api; } diff --git a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/CloseIncidentTests.cs b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/CloseIncidentTests.cs index 00e997930..400cb6125 100644 --- a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/CloseIncidentTests.cs +++ b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/CloseIncidentTests.cs @@ -5,34 +5,31 @@ namespace Helpdesk.Api.Tests.Incidents; -public class CloseIncidentTests: IClassFixture +public class CloseIncidentTests(ApiWithAcknowledgedIncident api): IClassFixture { [Fact] [Trait("Category", "Acceptance")] public async Task ResolveCommand_Succeeds() { - await API + await api .Given() .When( POST, - URI($"/api/agents/{agentId}/incidents/{API.Incident.Id}/close"), + URI($"/api/agents/{agentId}/incidents/{api.Incident.Id}/close"), HEADERS(IF_MATCH(3)) ) .Then(OK); - await API + await api .Given() - .When(GET, URI($"/api/incidents/{API.Incident.Id}")) + .When(GET, URI($"/api/incidents/{api.Incident.Id}")) .Then( OK, RESPONSE_BODY( - API.Incident with { Status = IncidentStatus.Closed, Version = 4 } + api.Incident with { Status = IncidentStatus.Closed, Version = 4 } ) ); } - private readonly ApiWithAcknowledgedIncident API; private Guid agentId = Guid.NewGuid(); - - public CloseIncidentTests(ApiWithAcknowledgedIncident api) => API = api; } diff --git a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/LogIncidentsTests.cs b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/LogIncidentsTests.cs index e27786124..ea128d5a7 100644 --- a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/LogIncidentsTests.cs +++ b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/LogIncidentsTests.cs @@ -8,11 +8,11 @@ namespace Helpdesk.Api.Tests.Incidents; -public class LogIncidentsTests: IClassFixture> +public class LogIncidentsTests(ApiSpecification api): IClassFixture> { [Fact] public Task LogIncident_ShouldSucceed() => - API.Given() + api.Given() .When( POST, URI($"api/customers/{CustomerId}/incidents/"), @@ -37,10 +37,6 @@ public class LogIncidentsTests: IClassFixture> ) ); - public LogIncidentsTests(ApiSpecification api) => API = api; - - private readonly ApiSpecification API; - private readonly Guid CustomerId = Guid.NewGuid(); private readonly Contact Contact = new Faker().CustomInstantiator( diff --git a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/PrioritiseIncidentTests.cs b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/PrioritiseIncidentTests.cs index cbec22cb9..2e0123fba 100644 --- a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/PrioritiseIncidentTests.cs +++ b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/PrioritiseIncidentTests.cs @@ -6,29 +6,29 @@ namespace Helpdesk.Api.Tests.Incidents; -public class PrioritiseIncidentTests: IClassFixture +public class PrioritiseIncidentTests(ApiWithLoggedIncident api): IClassFixture { [Fact] [Trait("Category", "Acceptance")] public async Task PrioritiseCommand_ChangesIncidentPriority() { - await API + await api .Given() .When( POST, - URI($"/api/agents/{agentId}/incidents/{API.Incident.Id}/priority"), + URI($"/api/agents/{agentId}/incidents/{api.Incident.Id}/priority"), BODY(new PrioritiseIncidentRequest(priority)), HEADERS(IF_MATCH(1)) ) .Then(OK); - await API + await api .Given() - .When(GET, URI($"/api/incidents/{API.Incident.Id}")) + .When(GET, URI($"/api/incidents/{api.Incident.Id}")) .Then( OK, RESPONSE_BODY( - API.Incident with + api.Incident with { Priority = priority, Version = 2 @@ -39,8 +39,4 @@ API.Incident with private readonly Guid agentId = Guid.NewGuid(); private readonly IncidentPriority priority = new Faker().PickRandom(); - private readonly ApiWithLoggedIncident API; - - public PrioritiseIncidentTests(ApiWithLoggedIncident api) => API = api; - } diff --git a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/RecordAgentResponseToIncidentTests.cs b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/RecordAgentResponseToIncidentTests.cs index 04f97115c..119ac49ce 100644 --- a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/RecordAgentResponseToIncidentTests.cs +++ b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/RecordAgentResponseToIncidentTests.cs @@ -7,29 +7,29 @@ namespace Helpdesk.Api.Tests.Incidents; -public class RecordAgentResponseToIncidentTests: IClassFixture +public class RecordAgentResponseToIncidentTests(ApiWithLoggedIncident api): IClassFixture { [Fact] [Trait("Category", "Acceptance")] public async Task RecordAgentResponseCommand_RecordsResponse() { - await API + await api .Given() .When( POST, - URI($"/api/agents/{agentId}/incidents/{API.Incident.Id}/responses"), + URI($"/api/agents/{agentId}/incidents/{api.Incident.Id}/responses"), BODY(new RecordAgentResponseToIncidentRequest(content, visibleToCustomer)), HEADERS(IF_MATCH(1)) ) .Then(OK); - await API + await api .Given() - .When(GET, URI($"/api/incidents/{API.Incident.Id}")) + .When(GET, URI($"/api/incidents/{api.Incident.Id}")) .Then( OK, RESPONSE_BODY( - API.Incident with + api.Incident with { Notes = [ @@ -44,7 +44,4 @@ API.Incident with private readonly Guid agentId = Guid.NewGuid(); private readonly string content = new Lorem().Sentence(); private readonly bool visibleToCustomer = new Faker().Random.Bool(); - private readonly ApiWithLoggedIncident API; - - public RecordAgentResponseToIncidentTests(ApiWithLoggedIncident api) => API = api; } diff --git a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/RecordCustomerResponseToIncidentTests.cs b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/RecordCustomerResponseToIncidentTests.cs index 8aa20ecc4..f8a56f1ae 100644 --- a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/RecordCustomerResponseToIncidentTests.cs +++ b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/RecordCustomerResponseToIncidentTests.cs @@ -6,29 +6,29 @@ namespace Helpdesk.Api.Tests.Incidents; -public class RecordCustomerResponseToIncidentTests: IClassFixture +public class RecordCustomerResponseToIncidentTests(ApiWithLoggedIncident api): IClassFixture { [Fact] [Trait("Category", "Acceptance")] public async Task RecordCustomerResponseCommand_RecordsResponse() { - await API + await api .Given() .When( POST, - URI($"/api/customers/{customerId}/incidents/{API.Incident.Id}/responses"), + URI($"/api/customers/{customerId}/incidents/{api.Incident.Id}/responses"), BODY(new RecordCustomerResponseToIncidentRequest(content)), HEADERS(IF_MATCH(1)) ) .Then(OK); - await API + await api .Given() - .When(GET, URI($"/api/incidents/{API.Incident.Id}")) + .When(GET, URI($"/api/incidents/{api.Incident.Id}")) .Then( OK, RESPONSE_BODY( - API.Incident with + api.Incident with { Notes = [new IncidentNote(IncidentNoteType.FromCustomer, customerId, content, true)], @@ -40,7 +40,4 @@ API.Incident with private readonly Guid customerId = Guid.NewGuid(); private readonly string content = new Lorem().Sentence(); - private readonly ApiWithLoggedIncident API; - - public RecordCustomerResponseToIncidentTests(ApiWithLoggedIncident api) => API = api; } diff --git a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/ResolveIncidentTests.cs b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/ResolveIncidentTests.cs index efcc866a5..71f65fb75 100644 --- a/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/ResolveIncidentTests.cs +++ b/Sample/Helpdesk/Helpdesk.Api.Tests/Incidents/ResolveIncidentTests.cs @@ -6,39 +6,36 @@ namespace Helpdesk.Api.Tests.Incidents; -public class ResolveIncidentTests: IClassFixture +public class ResolveIncidentTests(ApiWithLoggedIncident api): IClassFixture { [Fact] [Trait("Category", "Acceptance")] public async Task ResolveCommand_Succeeds() { - await API + await api .Given() .When( POST, - URI($"/api/agents/{agentId}/incidents/{API.Incident.Id}/resolve"), + URI($"/api/agents/{agentId}/incidents/{api.Incident.Id}/resolve"), BODY(new ResolveIncidentRequest(resolutionType)), HEADERS(IF_MATCH(1)) ) .Then(OK); - await API + await api .Given() .When( GET, - URI($"/api/incidents/{API.Incident.Id}") + URI($"/api/incidents/{api.Incident.Id}") ) .Then( OK, RESPONSE_BODY( - API.Incident with { Status = IncidentStatus.Resolved, Version = 2 } + api.Incident with { Status = IncidentStatus.Resolved, Version = 2 } ) ); } private readonly Guid agentId = Guid.NewGuid(); private readonly ResolutionType resolutionType = new Faker().PickRandom(); - private readonly ApiWithLoggedIncident API; - - public ResolveIncidentTests(ApiWithLoggedIncident api) => API = api; } diff --git a/Sample/HotelManagement/HotelManagement/Choreography/GroupCheckouts/GroupCheckoutDomainService.cs b/Sample/HotelManagement/HotelManagement/Choreography/GroupCheckouts/GroupCheckoutDomainService.cs index 33608d5f6..a2922802b 100644 --- a/Sample/HotelManagement/HotelManagement/Choreography/GroupCheckouts/GroupCheckoutDomainService.cs +++ b/Sample/HotelManagement/HotelManagement/Choreography/GroupCheckouts/GroupCheckoutDomainService.cs @@ -31,20 +31,14 @@ public record RecordGuestCheckoutFailure( DateTimeOffset FailedAt ); -public class GuestStayDomainService: - ICommandHandler, - IEventHandler, - IEventHandler, - IEventHandler +public class GuestStayDomainService(IDocumentSession documentSession, IAsyncCommandBus commandBus) + : + ICommandHandler, + IEventHandler, + IEventHandler, + IEventHandler { - private readonly IDocumentSession documentSession; - private readonly IAsyncCommandBus commandBus; - - public GuestStayDomainService(IDocumentSession documentSession, IAsyncCommandBus commandBus) - { - this.documentSession = documentSession; - this.commandBus = commandBus; - } + private readonly IAsyncCommandBus commandBus = commandBus; public Task Handle(InitiateGroupCheckout command, CancellationToken ct) => documentSession.Add( diff --git a/Sample/HotelManagement/HotelManagement/Choreography/GuestStayAccounts/GuestStayAccountDomainService.cs b/Sample/HotelManagement/HotelManagement/Choreography/GuestStayAccounts/GuestStayAccountDomainService.cs index 6e0ddaff9..55bd59f36 100644 --- a/Sample/HotelManagement/HotelManagement/Choreography/GuestStayAccounts/GuestStayAccountDomainService.cs +++ b/Sample/HotelManagement/HotelManagement/Choreography/GuestStayAccounts/GuestStayAccountDomainService.cs @@ -25,17 +25,12 @@ public record CheckOutGuest( Guid? GroupCheckOutId = null ); -public class GuestStayDomainService: +public class GuestStayDomainService(IDocumentSession documentSession): ICommandHandler, ICommandHandler, ICommandHandler, ICommandHandler { - private readonly IDocumentSession documentSession; - - public GuestStayDomainService(IDocumentSession documentSession) => - this.documentSession = documentSession; - public Task Handle(CheckInGuest command, CancellationToken ct) => documentSession.Add( command.GuestStayId, diff --git a/Sample/HotelManagement/HotelManagement/ProcessManagers/GroupCheckouts/GroupCheckoutDomainService.cs b/Sample/HotelManagement/HotelManagement/ProcessManagers/GroupCheckouts/GroupCheckoutDomainService.cs index 2d4221b11..72353e6f3 100644 --- a/Sample/HotelManagement/HotelManagement/ProcessManagers/GroupCheckouts/GroupCheckoutDomainService.cs +++ b/Sample/HotelManagement/HotelManagement/ProcessManagers/GroupCheckouts/GroupCheckoutDomainService.cs @@ -9,13 +9,8 @@ public record InitiateGroupCheckout( Guid[] GuestStayIds ); -public class GuestStayDomainService +public class GuestStayDomainService(IDocumentSession documentSession) { - private readonly IDocumentSession documentSession; - - public GuestStayDomainService(IDocumentSession documentSession) => - this.documentSession = documentSession; - public Task Handle(InitiateGroupCheckout command, CancellationToken ct) => documentSession.Add( command.GroupCheckoutId.ToString(), diff --git a/Sample/HotelManagement/HotelManagement/ProcessManagers/GuestStayAccounts/GuestStayAccountDomainService.cs b/Sample/HotelManagement/HotelManagement/ProcessManagers/GuestStayAccounts/GuestStayAccountDomainService.cs index 5826b8c8a..6d5b88dfa 100644 --- a/Sample/HotelManagement/HotelManagement/ProcessManagers/GuestStayAccounts/GuestStayAccountDomainService.cs +++ b/Sample/HotelManagement/HotelManagement/ProcessManagers/GuestStayAccounts/GuestStayAccountDomainService.cs @@ -22,13 +22,8 @@ public record CheckOutGuest( Guid? GroupCheckOutId = null ); -public class GuestStayDomainService +public class GuestStayDomainService(IDocumentSession documentSession) { - private readonly IDocumentSession documentSession; - - public GuestStayDomainService(IDocumentSession documentSession) => - this.documentSession = documentSession; - public Task Handle(CheckInGuest command, CancellationToken ct) => documentSession.Add( command.GuestStayId.ToString(), diff --git a/Sample/HotelManagement/HotelManagement/Sagas/GroupCheckouts/GroupCheckoutDomainService.cs b/Sample/HotelManagement/HotelManagement/Sagas/GroupCheckouts/GroupCheckoutDomainService.cs index 227035157..a10ee4a6b 100644 --- a/Sample/HotelManagement/HotelManagement/Sagas/GroupCheckouts/GroupCheckoutDomainService.cs +++ b/Sample/HotelManagement/HotelManagement/Sagas/GroupCheckouts/GroupCheckoutDomainService.cs @@ -27,17 +27,12 @@ public record RecordGuestCheckoutFailure( DateTimeOffset FailedAt ); -public class GuestStayDomainService: +public class GuestStayDomainService(IDocumentSession documentSession): ICommandHandler, ICommandHandler, ICommandHandler, ICommandHandler { - private readonly IDocumentSession documentSession; - - public GuestStayDomainService(IDocumentSession documentSession) => - this.documentSession = documentSession; - public Task Handle(InitiateGroupCheckout command, CancellationToken ct) => documentSession.Add( command.GroupCheckoutId, diff --git a/Sample/HotelManagement/HotelManagement/Sagas/GroupCheckouts/GroupCheckoutSaga.cs b/Sample/HotelManagement/HotelManagement/Sagas/GroupCheckouts/GroupCheckoutSaga.cs index 9203bb67f..5af770a73 100644 --- a/Sample/HotelManagement/HotelManagement/Sagas/GroupCheckouts/GroupCheckoutSaga.cs +++ b/Sample/HotelManagement/HotelManagement/Sagas/GroupCheckouts/GroupCheckoutSaga.cs @@ -4,16 +4,11 @@ namespace HotelManagement.Sagas.GroupCheckouts; -public class GroupCheckoutSaga: +public class GroupCheckoutSaga(IAsyncCommandBus commandBus): IEventHandler, IEventHandler, IEventHandler { - private readonly IAsyncCommandBus commandBus; - - public GroupCheckoutSaga(IAsyncCommandBus commandBus) => - this.commandBus = commandBus; - public async Task Handle(GroupCheckoutInitiated @event, CancellationToken ct) { foreach (var guestAccountId in @event.GuestStayIds) diff --git a/Sample/HotelManagement/HotelManagement/Sagas/GuestStayAccounts/GuestStayAccountDomainService.cs b/Sample/HotelManagement/HotelManagement/Sagas/GuestStayAccounts/GuestStayAccountDomainService.cs index 46bb262aa..cdc653cd7 100644 --- a/Sample/HotelManagement/HotelManagement/Sagas/GuestStayAccounts/GuestStayAccountDomainService.cs +++ b/Sample/HotelManagement/HotelManagement/Sagas/GuestStayAccounts/GuestStayAccountDomainService.cs @@ -25,17 +25,12 @@ public record CheckOutGuest( Guid? GroupCheckOutId = null ); -public class GuestStayDomainService: +public class GuestStayDomainService(IDocumentSession documentSession): ICommandHandler, ICommandHandler, ICommandHandler, ICommandHandler { - private readonly IDocumentSession documentSession; - - public GuestStayDomainService(IDocumentSession documentSession) => - this.documentSession = documentSession; - public Task Handle(CheckInGuest command, CancellationToken ct) => documentSession.Add( command.GuestStayId, diff --git a/Sample/HotelManagement/Reservations/RoomReservations/ReservingRoom/BookingComRoomReservationMadeHandler.cs b/Sample/HotelManagement/Reservations/RoomReservations/ReservingRoom/BookingComRoomReservationMadeHandler.cs index 71ca3dbc7..08679a493 100644 --- a/Sample/HotelManagement/Reservations/RoomReservations/ReservingRoom/BookingComRoomReservationMadeHandler.cs +++ b/Sample/HotelManagement/Reservations/RoomReservations/ReservingRoom/BookingComRoomReservationMadeHandler.cs @@ -22,19 +22,10 @@ DateTimeOffset MadeAt public delegate ValueTask GetGuestId(GetGuestIdByExternalId query, CancellationToken ct); -public class BookingComRoomReservationMadeHandler: IEventHandler +public class BookingComRoomReservationMadeHandler( + IDocumentSession session, + GetGuestId getGuestId): IEventHandler { - private readonly IDocumentSession session; - private readonly GetGuestId getGuestId; - - public BookingComRoomReservationMadeHandler( - IDocumentSession session, - GetGuestId getGuestId) - { - this.session = session; - this.getGuestId = getGuestId; - } - public async Task Handle(BookingComRoomReservationMade @event, CancellationToken ct) { var (bookingComReservationId, roomTypeText, from, to, bookingComGuestId, numberOfPeople, madeAt) = @event; diff --git a/Sample/MeetingsManagement/MeetingsManagement.Api/Controllers/MeetingsController.cs b/Sample/MeetingsManagement/MeetingsManagement.Api/Controllers/MeetingsController.cs index 092031e15..91812d101 100644 --- a/Sample/MeetingsManagement/MeetingsManagement.Api/Controllers/MeetingsController.cs +++ b/Sample/MeetingsManagement/MeetingsManagement.Api/Controllers/MeetingsController.cs @@ -10,17 +10,8 @@ namespace MeetingsManagement.Api.Controllers; [Route("api/[controller]")] -public class MeetingsController: Controller +public class MeetingsController(ICommandBus commandBus, IQueryBus queryBus): Controller { - private readonly ICommandBus commandBus; - private readonly IQueryBus queryBus; - - public MeetingsController(ICommandBus commandBus, IQueryBus queryBus) - { - this.commandBus = commandBus; - this.queryBus = queryBus; - } - [HttpGet("{id}")] public async Task Get(Guid id) { diff --git a/Sample/MeetingsManagement/MeetingsManagement.IntegrationTests/Meetings/CreatingMeeting/CreateMeetingTests.cs b/Sample/MeetingsManagement/MeetingsManagement.IntegrationTests/Meetings/CreatingMeeting/CreateMeetingTests.cs index ff36c2276..fdb788822 100644 --- a/Sample/MeetingsManagement/MeetingsManagement.IntegrationTests/Meetings/CreatingMeeting/CreateMeetingTests.cs +++ b/Sample/MeetingsManagement/MeetingsManagement.IntegrationTests/Meetings/CreatingMeeting/CreateMeetingTests.cs @@ -6,16 +6,11 @@ namespace MeetingsManagement.IntegrationTests.Meetings.CreatingMeeting; -public class CreateMeetingTests: IClassFixture> +public class CreateMeetingTests(TestWebApplicationFactory fixture) + : IClassFixture> { - private readonly ApiSpecification API; - private readonly TestWebApplicationFactory fixture; - - public CreateMeetingTests(TestWebApplicationFactory fixture) - { - this.fixture = fixture; - API = ApiSpecification.Setup(fixture); - } + private readonly ApiSpecification API = ApiSpecification.Setup(fixture); + private readonly TestWebApplicationFactory fixture = fixture; [Fact] [Trait("Category", "Acceptance")] diff --git a/Sample/MeetingsManagement/MeetingsManagement.IntegrationTests/Meetings/SchedulingMeetings/ScheduleMeetingTests.cs b/Sample/MeetingsManagement/MeetingsManagement.IntegrationTests/Meetings/SchedulingMeetings/ScheduleMeetingTests.cs index af7f5e697..23a95a4a1 100644 --- a/Sample/MeetingsManagement/MeetingsManagement.IntegrationTests/Meetings/SchedulingMeetings/ScheduleMeetingTests.cs +++ b/Sample/MeetingsManagement/MeetingsManagement.IntegrationTests/Meetings/SchedulingMeetings/ScheduleMeetingTests.cs @@ -8,18 +8,13 @@ namespace MeetingsManagement.IntegrationTests.Meetings.SchedulingMeetings; -public class ScheduleMeetingTests: IClassFixture> +public class ScheduleMeetingTests(ApiSpecification api): IClassFixture> { - - private readonly ApiSpecification API; - - public ScheduleMeetingTests(ApiSpecification api) => API = api; - [Fact] [Trait("Category", "Acceptance")] public async Task UpdateCommand_Should_Succeed() { - await API + await api .Given( "Created Meeting", SEND(POST, URI(MeetingsManagementApi.MeetingsUrl), BODY(new CreateMeeting(MeetingId, MeetingName))) diff --git a/Sample/MeetingsManagement/MeetingsManagement/Meetings/CreatingMeeting/CreateMeeting.cs b/Sample/MeetingsManagement/MeetingsManagement/Meetings/CreatingMeeting/CreateMeeting.cs index 340232371..e4d185210 100644 --- a/Sample/MeetingsManagement/MeetingsManagement/Meetings/CreatingMeeting/CreateMeeting.cs +++ b/Sample/MeetingsManagement/MeetingsManagement/Meetings/CreatingMeeting/CreateMeeting.cs @@ -8,14 +8,9 @@ public record CreateMeeting( string Name ); -internal class HandleCreateMeeting: +internal class HandleCreateMeeting(IMartenRepository repository): ICommandHandler { - private readonly IMartenRepository repository; - - public HandleCreateMeeting(IMartenRepository repository) => - this.repository = repository; - public Task Handle(CreateMeeting command, CancellationToken ct) { var (id, name) = command; diff --git a/Sample/MeetingsManagement/MeetingsManagement/Meetings/GettingMeeting/GetMeeting.cs b/Sample/MeetingsManagement/MeetingsManagement/Meetings/GettingMeeting/GetMeeting.cs index b9450b633..7daba937a 100644 --- a/Sample/MeetingsManagement/MeetingsManagement/Meetings/GettingMeeting/GetMeeting.cs +++ b/Sample/MeetingsManagement/MeetingsManagement/Meetings/GettingMeeting/GetMeeting.cs @@ -8,17 +8,8 @@ Guid Id ); -internal class HandleGetMeeting: IQueryHandler +internal class HandleGetMeeting(IQuerySession session): IQueryHandler { - private readonly IDocumentSession session; - - public HandleGetMeeting( - IDocumentSession session - ) - { - this.session = session ?? throw new ArgumentNullException(nameof(session)); - } - public Task Handle(GetMeeting request, CancellationToken cancellationToken) { return session.LoadAsync(request.Id, cancellationToken); diff --git a/Sample/MeetingsManagement/MeetingsManagement/Meetings/SchedulingMeeting/ScheduleMeeting.cs b/Sample/MeetingsManagement/MeetingsManagement/Meetings/SchedulingMeeting/ScheduleMeeting.cs index 0f8ea0c83..b74531140 100644 --- a/Sample/MeetingsManagement/MeetingsManagement/Meetings/SchedulingMeeting/ScheduleMeeting.cs +++ b/Sample/MeetingsManagement/MeetingsManagement/Meetings/SchedulingMeeting/ScheduleMeeting.cs @@ -9,14 +9,9 @@ public record ScheduleMeeting( DateRange Occurs ); -internal class HandleScheduleMeeting: +internal class HandleScheduleMeeting(IMartenRepository repository): ICommandHandler { - private readonly IMartenRepository repository; - - public HandleScheduleMeeting(IMartenRepository repository) => - this.repository = repository; - public Task Handle(ScheduleMeeting command, CancellationToken ct) { var (meetingId, dateRange) = command; diff --git a/Sample/MeetingsManagement/MeetingsManagement/Meetings/ValueObjects/DateRange.cs b/Sample/MeetingsManagement/MeetingsManagement/Meetings/ValueObjects/DateRange.cs index a5ae5a200..6d6423d3a 100644 --- a/Sample/MeetingsManagement/MeetingsManagement/Meetings/ValueObjects/DateRange.cs +++ b/Sample/MeetingsManagement/MeetingsManagement/Meetings/ValueObjects/DateRange.cs @@ -1,15 +1,9 @@ namespace MeetingsManagement.Meetings.ValueObjects; -public class DateRange +public class DateRange(DateTime start, DateTime end) { - public DateTime Start { get; } - public DateTime End { get; } - - public DateRange(DateTime start, DateTime end) - { - Start = start; - End = end; - } + public DateTime Start { get; } = start; + public DateTime End { get; } = end; public static DateRange Create(DateTime start, DateTime end) { @@ -24,4 +18,4 @@ public static DateRange Create(DateTime start, DateTime end) return new DateRange(start, end); } -} \ No newline at end of file +} diff --git a/Sample/MeetingsManagement/MeetingsSearch.Api/Controllers/MeetingsController.cs b/Sample/MeetingsManagement/MeetingsSearch.Api/Controllers/MeetingsController.cs index 96ae86eee..2c09cfadc 100644 --- a/Sample/MeetingsManagement/MeetingsSearch.Api/Controllers/MeetingsController.cs +++ b/Sample/MeetingsManagement/MeetingsSearch.Api/Controllers/MeetingsController.cs @@ -6,18 +6,11 @@ namespace MeetingsSearch.Api.Controllers; [Route("api/[controller]")] -public class MeetingsController: Controller +public class MeetingsController(IQueryBus queryBus): Controller { - private readonly IQueryBus queryBus; - - public MeetingsController(IQueryBus queryBus) - { - this.queryBus = queryBus; - } - [HttpGet] public Task> Search([FromQuery]string filter) { return queryBus.Query>(new SearchMeetings(filter)); } -} \ No newline at end of file +} diff --git a/Sample/MeetingsManagement/MeetingsSearch.IntegrationTests/Meetings/CreatingMeeting/CreateMeetingTests.cs b/Sample/MeetingsManagement/MeetingsSearch.IntegrationTests/Meetings/CreatingMeeting/CreateMeetingTests.cs index ad106290c..e9279331a 100644 --- a/Sample/MeetingsManagement/MeetingsSearch.IntegrationTests/Meetings/CreatingMeeting/CreateMeetingTests.cs +++ b/Sample/MeetingsManagement/MeetingsSearch.IntegrationTests/Meetings/CreatingMeeting/CreateMeetingTests.cs @@ -9,16 +9,10 @@ namespace MeetingsSearch.IntegrationTests.Meetings.CreatingMeeting; -public class CreateMeetingTests: IClassFixture> +public class CreateMeetingTests(TestWebApplicationFactory fixture) + : IClassFixture> { - private readonly ApiSpecification API; - private readonly TestWebApplicationFactory fixture; - - public CreateMeetingTests(TestWebApplicationFactory fixture) - { - this.fixture = fixture; - API = ApiSpecification.Setup(fixture); - } + private readonly ApiSpecification API = ApiSpecification.Setup(fixture); [Fact] [Trait("Category", "Acceptance")] diff --git a/Sample/MeetingsManagement/MeetingsSearch/Meetings/CreatingMeeting/MeetingCreated.cs b/Sample/MeetingsManagement/MeetingsSearch/Meetings/CreatingMeeting/MeetingCreated.cs index d216a6d6d..e02d72806 100644 --- a/Sample/MeetingsManagement/MeetingsSearch/Meetings/CreatingMeeting/MeetingCreated.cs +++ b/Sample/MeetingsManagement/MeetingsSearch/Meetings/CreatingMeeting/MeetingCreated.cs @@ -3,27 +3,14 @@ namespace MeetingsSearch.Meetings.CreatingMeeting; -internal class MeetingCreated +internal class MeetingCreated(Guid meetingId, string name) { - public Guid MeetingId { get; } - public string Name { get; } - - public MeetingCreated(Guid meetingId, string name) - { - MeetingId = meetingId; - Name = name; - } + public Guid MeetingId { get; } = meetingId; + public string Name { get; } = name; } -internal class HandleMeetingCreated: IEventHandler +internal class HandleMeetingCreated(IElasticSearchRepository repository): IEventHandler { - private readonly IElasticSearchRepository repository; - - public HandleMeetingCreated(IElasticSearchRepository repository) - { - this.repository = repository; - } - public Task Handle(MeetingCreated @event, CancellationToken cancellationToken) { var meeting = new Meeting(@event.MeetingId, @event.Name); diff --git a/Sample/MeetingsManagement/MeetingsSearch/Meetings/SearchingMeetings/SearchMeetings.cs b/Sample/MeetingsManagement/MeetingsSearch/Meetings/SearchingMeetings/SearchMeetings.cs index 6b1c72674..b84676d08 100644 --- a/Sample/MeetingsManagement/MeetingsSearch/Meetings/SearchingMeetings/SearchMeetings.cs +++ b/Sample/MeetingsManagement/MeetingsSearch/Meetings/SearchingMeetings/SearchMeetings.cs @@ -4,24 +4,17 @@ namespace MeetingsSearch.Meetings.SearchingMeetings; -public class SearchMeetings +public class SearchMeetings(string filter) { - public string Filter { get; } - - public SearchMeetings(string filter) - { - Filter = filter; - } + public string Filter { get; } = filter; } -internal class HandleSearchMeetings: IQueryHandler> +internal class HandleSearchMeetings(ElasticsearchClient elasticClient) + : IQueryHandler> { private const int MaxItemsCount = 1000; - private readonly ElasticsearchClient elasticClient; - - public HandleSearchMeetings(ElasticsearchClient elasticClient) => - this.elasticClient = elasticClient ?? throw new ArgumentNullException(nameof(elasticClient)); + private readonly ElasticsearchClient elasticClient = elasticClient ?? throw new ArgumentNullException(nameof(elasticClient)); public async Task> Handle(SearchMeetings query, CancellationToken cancellationToken) { diff --git a/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/EF/CommandHandler.cs b/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/EF/CommandHandler.cs index 0a1cff60d..adafea0ae 100644 --- a/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/EF/CommandHandler.cs +++ b/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/EF/CommandHandler.cs @@ -13,13 +13,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } } -public class ChemicalReactionCommandHandler +public class ChemicalReactionCommandHandler(EFRepository repository) { - private readonly EFRepository repository; - - public ChemicalReactionCommandHandler(EFRepository repository) => - this.repository = repository; - public Task Handle(ChemicalReactionCommand command, CancellationToken ct) => repository.GetAndUpdateAsync( command.Id, diff --git a/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/EF/EFRepository.cs b/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/EF/EFRepository.cs index f3550d9a0..66f39e36d 100644 --- a/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/EF/EFRepository.cs +++ b/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/EF/EFRepository.cs @@ -2,13 +2,10 @@ namespace SlimDownYourAggregate.Core.EF; -public class EFRepository where TDbContext : DbContext where T : class +public class EFRepository(TDbContext dbContext) + where TDbContext : DbContext + where T : class { - private readonly TDbContext dbContext; - - public EFRepository(TDbContext dbContext) => - this.dbContext = dbContext; - public ValueTask FindAsync(string id, CancellationToken ct) => dbContext.FindAsync(id, ct); diff --git a/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/Mongo/CommandHandler.cs b/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/Mongo/CommandHandler.cs index 9493fa229..a31c9c543 100644 --- a/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/Mongo/CommandHandler.cs +++ b/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/Mongo/CommandHandler.cs @@ -29,13 +29,8 @@ public record AddDummy(string Name); public record UpdateDummyName(string Id, string Name); -public class DummyCommandHandler +public class DummyCommandHandler(MongoRepository repository) { - private readonly MongoRepository repository; - - public DummyCommandHandler(MongoRepository repository) => - this.repository = repository; - public Task Handle(AddDummy command, CancellationToken ct) => repository.AddAsync(Dummy.Create(command.Name), ct); diff --git a/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/Mongo/MongoRepository.cs b/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/Mongo/MongoRepository.cs index aa338c4fb..07c679aab 100644 --- a/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/Mongo/MongoRepository.cs +++ b/Sample/SlimDownYourAggregate/SlimDownYourAggregate/Core/Mongo/MongoRepository.cs @@ -2,13 +2,8 @@ namespace SlimDownYourAggregate.Core.Mongo; -public class MongoRepository +public class MongoRepository(IMongoCollection collection) { - private readonly IMongoCollection collection; - - public MongoRepository(IMongoCollection collection) => - this.collection = collection; - public async Task FindAsync(string id, CancellationToken ct) => await collection.Find(Builders.Filter.Eq("_id", id)).SingleOrDefaultAsync(ct); diff --git a/Sample/SlimDownYourAggregate/SlimDownYourAggregate/InitialAggregate.cs b/Sample/SlimDownYourAggregate/SlimDownYourAggregate/InitialAggregate.cs index 9747cb8d6..04fdf1927 100644 --- a/Sample/SlimDownYourAggregate/SlimDownYourAggregate/InitialAggregate.cs +++ b/Sample/SlimDownYourAggregate/SlimDownYourAggregate/InitialAggregate.cs @@ -55,20 +55,12 @@ public enum ReactionState Completed } -public class ReactionParticipant +public class ReactionParticipant(Guid id, string chemicalName, double moles, ParticipantType type) { - public Guid Id { get; private set; } - public string ChemicalName { get; private set; } - public double Moles { get; private set; } - public ParticipantType Type { get; private set; } - - public ReactionParticipant(Guid id, string chemicalName, double moles, ParticipantType type) - { - Id = id; - ChemicalName = chemicalName; - Moles = moles; - Type = type; - } + public Guid Id { get; private set; } = id; + public string ChemicalName { get; private set; } = chemicalName; + public double Moles { get; private set; } = moles; + public ParticipantType Type { get; private set; } = type; public void UpdateMoles(double newMoles) { diff --git a/Sample/SlimDownYourAggregate/SlimDownYourAggregate/SlimmedAggregate.cs b/Sample/SlimDownYourAggregate/SlimDownYourAggregate/SlimmedAggregate.cs index 2d0625107..2f4d5f9fc 100644 --- a/Sample/SlimDownYourAggregate/SlimDownYourAggregate/SlimmedAggregate.cs +++ b/Sample/SlimDownYourAggregate/SlimDownYourAggregate/SlimmedAggregate.cs @@ -162,16 +162,10 @@ public record InProgress: ChemicalReaction public record Completed: ChemicalReaction; } -public class ReactionParticipant +public class ReactionParticipant(double moles, ParticipantType type) { - public double Moles { get; private set; } - public ParticipantType Type { get; private set; } - - public ReactionParticipant(double moles, ParticipantType type) - { - Moles = moles; - Type = type; - } + public double Moles { get; private set; } = moles; + public ParticipantType Type { get; private set; } = type; public void UpdateMoles(double newMoles) { diff --git a/Sample/Tickets/Tickets.Api.Tests/Reservations/CreatingTentativeReservation/CreateTentativeReservationTests.cs b/Sample/Tickets/Tickets.Api.Tests/Reservations/CreatingTentativeReservation/CreateTentativeReservationTests.cs index 1e09ab584..bf6e24e5e 100644 --- a/Sample/Tickets/Tickets.Api.Tests/Reservations/CreatingTentativeReservation/CreateTentativeReservationTests.cs +++ b/Sample/Tickets/Tickets.Api.Tests/Reservations/CreatingTentativeReservation/CreateTentativeReservationTests.cs @@ -12,7 +12,8 @@ namespace Tickets.Api.Tests.Reservations.CreatingTentativeReservation; -public class CreateTentativeReservationTests: IClassFixture> +public class CreateTentativeReservationTests(TestWebApplicationFactory fixture) + : IClassFixture> { [Fact] public Task Post_ShouldReturn_CreatedStatus_With_CartId() => @@ -77,8 +78,5 @@ public class CreateTentativeReservationTests: IClassFixture API; - - public CreateTentativeReservationTests(TestWebApplicationFactory fixture) => - API = ApiSpecification.Setup(fixture); + private readonly ApiSpecification API = ApiSpecification.Setup(fixture); } diff --git a/Sample/Tickets/Tickets.Api/Controllers/MaintenanceController.cs b/Sample/Tickets/Tickets.Api/Controllers/MaintenanceController.cs index 56a7b230a..5ac8d84b1 100644 --- a/Sample/Tickets/Tickets.Api/Controllers/MaintenanceController.cs +++ b/Sample/Tickets/Tickets.Api/Controllers/MaintenanceController.cs @@ -6,16 +6,8 @@ namespace Tickets.Api.Controllers; [Route("api/[controller]")] -public class MaintenanceController: Controller +public class MaintenanceController(ICommandBus commandBus): Controller { - private readonly ICommandBus commandBus; - - public MaintenanceController( - ICommandBus commandBus) - { - this.commandBus = commandBus; - } - [HttpPost("projections/rebuild")] public async Task Rebuild([FromBody] RebuildProjectionRequest request) { @@ -30,4 +22,4 @@ public async Task Rebuild([FromBody] RebuildProjectionRequest req return Accepted(); } -} \ No newline at end of file +} diff --git a/Sample/Tickets/Tickets.Api/Controllers/ReservationsController.cs b/Sample/Tickets/Tickets.Api/Controllers/ReservationsController.cs index 695ab878a..37703981e 100644 --- a/Sample/Tickets/Tickets.Api/Controllers/ReservationsController.cs +++ b/Sample/Tickets/Tickets.Api/Controllers/ReservationsController.cs @@ -17,23 +17,12 @@ namespace Tickets.Api.Controllers; [Route("api/[controller]")] -public class ReservationsController: Controller +public class ReservationsController( + ICommandBus commandBus, + IQueryBus queryBus, + IIdGenerator idGenerator) + : Controller { - private readonly ICommandBus commandBus; - private readonly IQueryBus queryBus; - - private readonly IIdGenerator idGenerator; - - public ReservationsController( - ICommandBus commandBus, - IQueryBus queryBus, - IIdGenerator idGenerator) - { - this.commandBus = commandBus; - this.queryBus = queryBus; - this.idGenerator = idGenerator; - } - [HttpGet("{id}")] public Task Get(Guid id) { diff --git a/Sample/Tickets/Tickets/Concerts/Concert.cs b/Sample/Tickets/Tickets/Concerts/Concert.cs index af110990f..cb469b0b5 100644 --- a/Sample/Tickets/Tickets/Concerts/Concert.cs +++ b/Sample/Tickets/Tickets/Concerts/Concert.cs @@ -2,15 +2,9 @@ namespace Tickets.Concerts; -public class Concert : Aggregate +public class Concert(string name, DateTime date): Aggregate { - public string Name { get; private set; } + public string Name { get; private set; } = name; - public DateTime Date { get; private set; } - - public Concert(string name, DateTime date) - { - Name = name; - Date = date; - } -} \ No newline at end of file + public DateTime Date { get; private set; } = date; +} diff --git a/Sample/Tickets/Tickets/Maintenance/MaintenanceCommandHandler.cs b/Sample/Tickets/Tickets/Maintenance/MaintenanceCommandHandler.cs index a3813aac8..a34660548 100644 --- a/Sample/Tickets/Tickets/Maintenance/MaintenanceCommandHandler.cs +++ b/Sample/Tickets/Tickets/Maintenance/MaintenanceCommandHandler.cs @@ -4,16 +4,9 @@ namespace Tickets.Maintenance; -public class MaintenanceCommandHandler: +public class MaintenanceCommandHandler(IDocumentStore documentStore): ICommandHandler { - private readonly IDocumentStore documentStore; - - public MaintenanceCommandHandler(IDocumentStore documentStore) - { - this.documentStore = documentStore; - } - public async Task Handle(RebuildProjection command, CancellationToken ct) { using var daemon = await documentStore.BuildProjectionDaemonAsync(); diff --git a/Sample/Tickets/Tickets/Reservations/CancellingReservation/CancelReservation.cs b/Sample/Tickets/Tickets/Reservations/CancellingReservation/CancelReservation.cs index 03f4ecb08..fcd82f5ed 100644 --- a/Sample/Tickets/Tickets/Reservations/CancellingReservation/CancelReservation.cs +++ b/Sample/Tickets/Tickets/Reservations/CancellingReservation/CancelReservation.cs @@ -16,14 +16,9 @@ public static CancelReservation Create(Guid? reservationId) } } -internal class HandleCancelReservation: +internal class HandleCancelReservation(IMartenRepository repository): ICommandHandler { - private readonly IMartenRepository repository; - - public HandleCancelReservation(IMartenRepository repository) => - this.repository = repository; - public Task Handle(CancelReservation command, CancellationToken ct) => repository.GetAndUpdate( command.ReservationId, diff --git a/Sample/Tickets/Tickets/Reservations/ChangingReservationSeat/ChangeReservationSeat.cs b/Sample/Tickets/Tickets/Reservations/ChangingReservationSeat/ChangeReservationSeat.cs index 04a344df6..5366ab79c 100644 --- a/Sample/Tickets/Tickets/Reservations/ChangingReservationSeat/ChangeReservationSeat.cs +++ b/Sample/Tickets/Tickets/Reservations/ChangingReservationSeat/ChangeReservationSeat.cs @@ -22,14 +22,9 @@ public static ChangeReservationSeat Create(Guid? reservationId, Guid? seatId) } } -internal class HandleChangeReservationSeat: +internal class HandleChangeReservationSeat(IMartenRepository repository): ICommandHandler { - private readonly IMartenRepository repository; - - public HandleChangeReservationSeat(IMartenRepository repository) => - this.repository = repository; - public Task Handle(ChangeReservationSeat command, CancellationToken ct) => repository.GetAndUpdate( command.ReservationId, diff --git a/Sample/Tickets/Tickets/Reservations/ConfirmingReservation/ConfirmReservation.cs b/Sample/Tickets/Tickets/Reservations/ConfirmingReservation/ConfirmReservation.cs index 3e895863d..f6de95416 100644 --- a/Sample/Tickets/Tickets/Reservations/ConfirmingReservation/ConfirmReservation.cs +++ b/Sample/Tickets/Tickets/Reservations/ConfirmingReservation/ConfirmReservation.cs @@ -16,14 +16,9 @@ public static ConfirmReservation Create(Guid? reservationId) } } -internal class HandleConfirmReservation: +internal class HandleConfirmReservation(IMartenRepository repository): ICommandHandler { - private readonly IMartenRepository repository; - - public HandleConfirmReservation(IMartenRepository repository) => - this.repository = repository; - public Task Handle(ConfirmReservation command, CancellationToken ct) => repository.GetAndUpdate( command.ReservationId, diff --git a/Sample/Tickets/Tickets/Reservations/CreatingTentativeReservation/CreateTentativeReservation.cs b/Sample/Tickets/Tickets/Reservations/CreatingTentativeReservation/CreateTentativeReservation.cs index 9a2629d96..3f8297364 100644 --- a/Sample/Tickets/Tickets/Reservations/CreatingTentativeReservation/CreateTentativeReservation.cs +++ b/Sample/Tickets/Tickets/Reservations/CreatingTentativeReservation/CreateTentativeReservation.cs @@ -20,21 +20,12 @@ public static CreateTentativeReservation Create(Guid? reservationId, Guid? seatI } } -internal class HandleCreateTentativeReservation: - ICommandHandler +internal class HandleCreateTentativeReservation( + IMartenRepository repository, + IReservationNumberGenerator reservationNumberGenerator) + : + ICommandHandler { - private readonly IMartenRepository repository; - private readonly IReservationNumberGenerator reservationNumberGenerator; - - public HandleCreateTentativeReservation( - IMartenRepository repository, - IReservationNumberGenerator reservationNumberGenerator - ) - { - this.repository = repository; - this.reservationNumberGenerator = reservationNumberGenerator; - } - public Task Handle(CreateTentativeReservation command, CancellationToken ct) { var (reservationId, seatId) = command; diff --git a/Sample/Tickets/Tickets/Reservations/GettingReservationAtVersion/GetReservationAtVersion.cs b/Sample/Tickets/Tickets/Reservations/GettingReservationAtVersion/GetReservationAtVersion.cs index 0efb943f2..e56038988 100644 --- a/Sample/Tickets/Tickets/Reservations/GettingReservationAtVersion/GetReservationAtVersion.cs +++ b/Sample/Tickets/Tickets/Reservations/GettingReservationAtVersion/GetReservationAtVersion.cs @@ -21,16 +21,9 @@ public static GetReservationAtVersion Create(Guid reservationId, int version) } } -internal class HandleGetReservationAtVersion: +internal class HandleGetReservationAtVersion(IDocumentSession querySession): IQueryHandler { - private readonly IDocumentSession querySession; - - public HandleGetReservationAtVersion(IDocumentSession querySession) - { - this.querySession = querySession; - } - public async Task Handle(GetReservationAtVersion query, CancellationToken cancellationToken) { var (reservationId, version) = query; diff --git a/Sample/Tickets/Tickets/Reservations/GettingReservationById/GetReservationById.cs b/Sample/Tickets/Tickets/Reservations/GettingReservationById/GetReservationById.cs index 73811d88b..bc022d260 100644 --- a/Sample/Tickets/Tickets/Reservations/GettingReservationById/GetReservationById.cs +++ b/Sample/Tickets/Tickets/Reservations/GettingReservationById/GetReservationById.cs @@ -9,16 +9,9 @@ Guid ReservationId ); -internal class HandleGetReservationById : +internal class HandleGetReservationById(IDocumentSession querySession): IQueryHandler { - private readonly IDocumentSession querySession; - - public HandleGetReservationById(IDocumentSession querySession) - { - this.querySession = querySession; - } - public async Task Handle(GetReservationById request, CancellationToken cancellationToken) { return await querySession.LoadAsync(request.ReservationId, cancellationToken) diff --git a/Sample/Tickets/Tickets/Reservations/GettingReservationHistory/GetReservationHistory.cs b/Sample/Tickets/Tickets/Reservations/GettingReservationHistory/GetReservationHistory.cs index 86a9992fa..15a040aa0 100644 --- a/Sample/Tickets/Tickets/Reservations/GettingReservationHistory/GetReservationHistory.cs +++ b/Sample/Tickets/Tickets/Reservations/GettingReservationHistory/GetReservationHistory.cs @@ -21,16 +21,9 @@ public static GetReservationHistory Create(Guid reservationId, int pageNumber = } } -internal class HandleGetReservationHistory: +internal class HandleGetReservationHistory(IDocumentSession querySession): IQueryHandler> { - private readonly IDocumentSession querySession; - - public HandleGetReservationHistory(IDocumentSession querySession) - { - this.querySession = querySession; - } - public Task> Handle( GetReservationHistory query, CancellationToken cancellationToken diff --git a/Sample/Tickets/Tickets/Reservations/GettingReservations/GetReservations.cs b/Sample/Tickets/Tickets/Reservations/GettingReservations/GetReservations.cs index 86670cdaf..0a15485de 100644 --- a/Sample/Tickets/Tickets/Reservations/GettingReservations/GetReservations.cs +++ b/Sample/Tickets/Tickets/Reservations/GettingReservations/GetReservations.cs @@ -20,16 +20,9 @@ public static GetReservations Create(int pageNumber = 1, int pageSize = 20) } } -internal class HandleGetReservations: +internal class HandleGetReservations(IDocumentSession querySession): IQueryHandler> { - private readonly IDocumentSession querySession; - - public HandleGetReservations(IDocumentSession querySession) - { - this.querySession = querySession; - } - public Task> Handle( GetReservations query, CancellationToken cancellationToken diff --git a/Sample/Tickets/Tickets/Seats/Seat.cs b/Sample/Tickets/Tickets/Seats/Seat.cs index 59064ada6..e0d26dfc1 100644 --- a/Sample/Tickets/Tickets/Seats/Seat.cs +++ b/Sample/Tickets/Tickets/Seats/Seat.cs @@ -2,18 +2,11 @@ namespace Tickets.Seats; -public class Seat : Aggregate +public class Seat(Guid concertId, string number, decimal price): Aggregate { - public Guid ConcertId { get; private set; } + public Guid ConcertId { get; private set; } = concertId; - public string Number { get; private set; } + public string Number { get; private set; } = number; - public decimal Price { get; private set; } - - public Seat(Guid concertId, string number, decimal price) - { - ConcertId = concertId; - Number = number; - Price = price; - } -} \ No newline at end of file + public decimal Price { get; private set; } = price; +} diff --git a/Sample/Tickets/Tickets/Tickets/Ticket.cs b/Sample/Tickets/Tickets/Tickets/Ticket.cs index 1cbb3731e..408691ca9 100644 --- a/Sample/Tickets/Tickets/Tickets/Ticket.cs +++ b/Sample/Tickets/Tickets/Tickets/Ticket.cs @@ -2,15 +2,9 @@ namespace Tickets.Tickets; -public class Ticket : Aggregate +public class Ticket(Guid seatId, string number): Aggregate { - public Guid SeatId { get; private set; } + public Guid SeatId { get; private set; } = seatId; - public string Number { get; private set; } - - public Ticket(Guid seatId, string number) - { - SeatId = seatId; - Number = number; - } + public string Number { get; private set; } = number; } diff --git a/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/GetProductDetails.cs b/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/GetProductDetails.cs index 90b9281a0..7e3b664f2 100644 --- a/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/GetProductDetails.cs +++ b/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/GetProductDetails.cs @@ -4,15 +4,8 @@ namespace Warehouse.Api.Products; -internal class HandleGetProductDetails: IQueryHandler +internal class HandleGetProductDetails(IQueryable products): IQueryHandler { - private readonly IQueryable products; - - public HandleGetProductDetails(IQueryable products) - { - this.products = products; - } - public async ValueTask Handle(GetProductDetails query, CancellationToken ct) { var product = await products diff --git a/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/GetProducts.cs b/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/GetProducts.cs index 4e78bdc3a..549fee359 100644 --- a/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/GetProducts.cs +++ b/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/GetProducts.cs @@ -3,15 +3,9 @@ namespace Warehouse.Api.Products; -internal class HandleGetProducts : IQueryHandler> +internal class HandleGetProducts(IQueryable products) + : IQueryHandler> { - private readonly IQueryable products; - - public HandleGetProducts(IQueryable products) - { - this.products = products; - } - public async ValueTask> Handle(GetProducts query, CancellationToken ct) { var (filter, page, pageSize) = query; diff --git a/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/Product.cs b/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/Product.cs index 4f3e7d86c..7b6585522 100644 --- a/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/Product.cs +++ b/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/Product.cs @@ -34,16 +34,9 @@ public Product(Guid id, SKU sku, string name, string? description) } } -public record SKU +[method: JsonConstructor] +public record SKU(string Value) { - public string Value { get; init; } - - [JsonConstructor] - public SKU(string value) - { - Value = value; - } - public static SKU Create(string? value) { if (value == null) diff --git a/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/RegisterProduct.cs b/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/RegisterProduct.cs index 3cb2842ee..d9eb643f7 100644 --- a/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/RegisterProduct.cs +++ b/Sample/Warehouse.MinimalAPI/Warehouse.Api/Products/RegisterProduct.cs @@ -2,20 +2,11 @@ namespace Warehouse.Api.Products; -internal class HandleRegisterProduct : ICommandHandler +internal class HandleRegisterProduct( + Func addProduct, + Func> productWithSKUExists) + : ICommandHandler { - private readonly Func addProduct; - private readonly Func> productWithSKUExists; - - public HandleRegisterProduct( - Func addProduct, - Func> productWithSKUExists - ) - { - this.addProduct = addProduct; - this.productWithSKUExists = productWithSKUExists; - } - public async Task Handle(RegisterProduct command, CancellationToken ct) { var product = new Product( diff --git a/Sample/Warehouse.MinimalAPI/Warehouse.Api/Storage/WarehouseDBContext.cs b/Sample/Warehouse.MinimalAPI/Warehouse.Api/Storage/WarehouseDBContext.cs index 1b3e63c23..96362d245 100644 --- a/Sample/Warehouse.MinimalAPI/Warehouse.Api/Storage/WarehouseDBContext.cs +++ b/Sample/Warehouse.MinimalAPI/Warehouse.Api/Storage/WarehouseDBContext.cs @@ -4,14 +4,8 @@ namespace Warehouse.Api.Storage; -public class WarehouseDBContext: DbContext +public class WarehouseDBContext(DbContextOptions options): DbContext(options) { - public WarehouseDBContext(DbContextOptions options) - : base(options) - { - - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.SetupProductsModel(); diff --git a/Sample/Warehouse/Warehouse.Api.Tests/Products/GettingProductDetails/GetProductDetailsTests.cs b/Sample/Warehouse/Warehouse.Api.Tests/Products/GettingProductDetails/GetProductDetailsTests.cs index ac7214cdf..50adc9507 100644 --- a/Sample/Warehouse/Warehouse.Api.Tests/Products/GettingProductDetails/GetProductDetailsTests.cs +++ b/Sample/Warehouse/Warehouse.Api.Tests/Products/GettingProductDetails/GetProductDetailsTests.cs @@ -6,40 +6,35 @@ namespace Warehouse.Api.Tests.Products.GettingProductDetails; -public class GetProductDetailsTests: IClassFixture +public class GetProductDetailsTests(GetProductDetailsFixture api): IClassFixture { - private readonly GetProductDetailsFixture API; - - public GetProductDetailsTests(GetProductDetailsFixture api) => API = api; - [Fact] public Task ValidRequest_With_NoParams_ShouldReturn_200() => - API.Given() - .When(GET, URI($"/api/products/{API.ExistingProduct.Id}")) - .Then(OK, RESPONSE_BODY(API.ExistingProduct)); + api.Given() + .When(GET, URI($"/api/products/{api.ExistingProduct.Id}")) + .Then(OK, RESPONSE_BODY(api.ExistingProduct)); [Theory] [InlineData(12)] [InlineData("not-a-guid")] public Task InvalidGuidId_ShouldReturn_404(object invalidId) => - API.Given() + api.Given() .When(GET, URI($"/api/products/{invalidId}")) .Then(NOT_FOUND); [Fact] public Task NotExistingId_ShouldReturn_404() => - API.Given() + api.Given() .When(GET, URI($"/api/products/{Guid.NewGuid()}")) .Then(NOT_FOUND); } -public class GetProductDetailsFixture: ApiSpecification, IAsyncLifetime +public class GetProductDetailsFixture() + : ApiSpecification(new WarehouseTestWebApplicationFactory()), IAsyncLifetime { public ProductDetails ExistingProduct = default!; - public GetProductDetailsFixture(): base(new WarehouseTestWebApplicationFactory()) { } - public async Task InitializeAsync() { var registerProduct = new RegisterProductRequest("IN11111", "ValidName", "ValidDescription"); diff --git a/Sample/Warehouse/Warehouse.Api.Tests/Products/GettingProducts/GetProductsTests.cs b/Sample/Warehouse/Warehouse.Api.Tests/Products/GettingProducts/GetProductsTests.cs index 901df78df..8d8ce6e76 100644 --- a/Sample/Warehouse/Warehouse.Api.Tests/Products/GettingProducts/GetProductsTests.cs +++ b/Sample/Warehouse/Warehouse.Api.Tests/Products/GettingProducts/GetProductsTests.cs @@ -6,26 +6,21 @@ namespace Warehouse.Api.Tests.Products.GettingProducts; -public class GetProductsTests: IClassFixture +public class GetProductsTests(GetProductsFixture api): IClassFixture { - private readonly GetProductsFixture API; - - public GetProductsTests(GetProductsFixture api) => - API = api; - [Fact] public Task ValidRequest_With_NoParams_ShouldReturn_200() => - API.Given() + api.Given() .When(GET, URI("/api/products/")) - .Then(OK, RESPONSE_BODY(API.RegisteredProducts)); + .Then(OK, RESPONSE_BODY(api.RegisteredProducts)); [Fact] public Task ValidRequest_With_Filter_ShouldReturn_SubsetOfRecords() { - var registeredProduct = API.RegisteredProducts.First(); + var registeredProduct = api.RegisteredProducts.First(); var filter = registeredProduct.Sku[1..]; - return API.Given() + return api.Given() .When(GET, URI($"/api/products/?filter={filter}")) .Then(OK, RESPONSE_BODY(new List { registeredProduct })); } @@ -36,19 +31,19 @@ public Task ValidRequest_With_Paging_ShouldReturn_PageOfRecords() // Given const int page = 2; const int pageSize = 1; - var pagedRecords = API.RegisteredProducts + var pagedRecords = api.RegisteredProducts .Skip(page - 1) .Take(pageSize) .ToList(); - return API.Given() + return api.Given() .When(GET, URI($"/api/products/?page={page}&pageSize={pageSize}")) .Then(OK, RESPONSE_BODY(pagedRecords)); } [Fact] public Task NegativePage_ShouldReturn_400() => - API.Given() + api.Given() .When(GET, URI($"/api/products/?page={-20}")) .Then(BAD_REQUEST); @@ -56,18 +51,16 @@ public Task ValidRequest_With_Paging_ShouldReturn_PageOfRecords() [InlineData(0)] [InlineData(-20)] public Task NegativeOrZeroPageSize_ShouldReturn_400(int pageSize) => - API.Given() + api.Given() .When(GET, URI($"/api/products/?pageSize={pageSize}")) .Then(BAD_REQUEST); } -public class GetProductsFixture: ApiSpecification, IAsyncLifetime +public class GetProductsFixture(): ApiSpecification(new WarehouseTestWebApplicationFactory()), IAsyncLifetime { public List RegisteredProducts { get; } = []; - public GetProductsFixture(): base(new WarehouseTestWebApplicationFactory()) { } - public async Task InitializeAsync() { var productsToRegister = new[] diff --git a/Sample/Warehouse/Warehouse.Api.Tests/Products/RegisteringProduct/RegisterProductTests.cs b/Sample/Warehouse/Warehouse.Api.Tests/Products/RegisteringProduct/RegisterProductTests.cs index c851dac5c..e534275d0 100644 --- a/Sample/Warehouse/Warehouse.Api.Tests/Products/RegisteringProduct/RegisterProductTests.cs +++ b/Sample/Warehouse/Warehouse.Api.Tests/Products/RegisteringProduct/RegisterProductTests.cs @@ -6,12 +6,10 @@ namespace Warehouse.Api.Tests.Products.RegisteringProduct; -public class RegisterProductTests: IClassFixture +public class RegisterProductTests(WarehouseTestWebApplicationFactory webApplicationFactory) + : IClassFixture { - private readonly ApiSpecification API; - - public RegisterProductTests(WarehouseTestWebApplicationFactory webApplicationFactory) => - API = ApiSpecification.Setup(webApplicationFactory); + private readonly ApiSpecification API = ApiSpecification.Setup(webApplicationFactory); [Theory] [MemberData(nameof(ValidRequests))] diff --git a/Sample/Warehouse/Warehouse/Products/GettingProductDetails/GetProductDetails.cs b/Sample/Warehouse/Warehouse/Products/GettingProductDetails/GetProductDetails.cs index b8559fee4..335a10141 100644 --- a/Sample/Warehouse/Warehouse/Products/GettingProductDetails/GetProductDetails.cs +++ b/Sample/Warehouse/Warehouse/Products/GettingProductDetails/GetProductDetails.cs @@ -4,15 +4,8 @@ namespace Warehouse.Products.GettingProductDetails; -internal class HandleGetProductDetails: IQueryHandler +internal class HandleGetProductDetails(IQueryable products): IQueryHandler { - private readonly IQueryable products; - - public HandleGetProductDetails(IQueryable products) - { - this.products = products; - } - public async ValueTask Handle(GetProductDetails query, CancellationToken ct) { // await is needed because of https://github.com/dotnet/efcore/issues/21793#issuecomment-667096367 @@ -49,4 +42,4 @@ public record ProductDetails( string Sku, string Name, string? Description -); \ No newline at end of file +); diff --git a/Sample/Warehouse/Warehouse/Products/GettingProducts/GetProducts.cs b/Sample/Warehouse/Warehouse/Products/GettingProducts/GetProducts.cs index 6e459477f..cb9e3c42e 100644 --- a/Sample/Warehouse/Warehouse/Products/GettingProducts/GetProducts.cs +++ b/Sample/Warehouse/Warehouse/Products/GettingProducts/GetProducts.cs @@ -3,15 +3,9 @@ namespace Warehouse.Products.GettingProducts; -internal class HandleGetProducts : IQueryHandler> +internal class HandleGetProducts(IQueryable products) + : IQueryHandler> { - private readonly IQueryable products; - - public HandleGetProducts(IQueryable products) - { - this.products = products; - } - public async ValueTask> Handle(GetProducts query, CancellationToken ct) { var (filter, page, pageSize) = query; @@ -78,4 +72,4 @@ public record ProductListItem( Guid Id, string Sku, string Name -); \ No newline at end of file +); diff --git a/Sample/Warehouse/Warehouse/Products/RegisteringProduct/RegisterProduct.cs b/Sample/Warehouse/Warehouse/Products/RegisteringProduct/RegisterProduct.cs index 6de17d81a..911025d0b 100644 --- a/Sample/Warehouse/Warehouse/Products/RegisteringProduct/RegisterProduct.cs +++ b/Sample/Warehouse/Warehouse/Products/RegisteringProduct/RegisterProduct.cs @@ -3,20 +3,11 @@ namespace Warehouse.Products.RegisteringProduct; -internal class HandleRegisterProduct : ICommandHandler +internal class HandleRegisterProduct( + Func addProduct, + Func> productWithSKUExists) + : ICommandHandler { - private readonly Func addProduct; - private readonly Func> productWithSKUExists; - - public HandleRegisterProduct( - Func addProduct, - Func> productWithSKUExists - ) - { - this.addProduct = addProduct; - this.productWithSKUExists = productWithSKUExists; - } - public async Task Handle(RegisterProduct command, CancellationToken ct) { var product = new Product( diff --git a/Sample/Warehouse/Warehouse/Storage/WarehouseDBContext.cs b/Sample/Warehouse/Warehouse/Storage/WarehouseDBContext.cs index dc956095e..2500b6233 100644 --- a/Sample/Warehouse/Warehouse/Storage/WarehouseDBContext.cs +++ b/Sample/Warehouse/Warehouse/Storage/WarehouseDBContext.cs @@ -5,14 +5,8 @@ namespace Warehouse.Storage; -public class WarehouseDBContext: DbContext +public class WarehouseDBContext(DbContextOptions options): DbContext(options) { - public WarehouseDBContext(DbContextOptions options) - : base(options) - { - - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.SetupProductsModel(); @@ -47,4 +41,4 @@ public WarehouseDBContext CreateDbContext(params string[] args) public static WarehouseDBContext Create() => new WarehouseDBContextFactory().CreateDbContext(); -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/01-CreateStreamsTable/EventStore.cs b/Workshops/BuildYourOwnEventStore/01-CreateStreamsTable/EventStore.cs index 6e663ac59..a6b0c58cd 100644 --- a/Workshops/BuildYourOwnEventStore/01-CreateStreamsTable/EventStore.cs +++ b/Workshops/BuildYourOwnEventStore/01-CreateStreamsTable/EventStore.cs @@ -2,15 +2,8 @@ namespace EventStoreBasics; -public class EventStore: IDisposable, IEventStore +public class EventStore(NpgsqlConnection databaseConnection): IDisposable, IEventStore { - private readonly NpgsqlConnection databaseConnection; - - public EventStore(NpgsqlConnection databaseConnection) - { - this.databaseConnection = databaseConnection; - } - public void Init() { // See more in Greg Young's "Building an Event Storage" article https://cqrs.wordpress.com/documents/building-event-storage/ @@ -26,4 +19,4 @@ public void Dispose() { databaseConnection.Dispose(); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/02-CreateEventsTable/EventStore.cs b/Workshops/BuildYourOwnEventStore/02-CreateEventsTable/EventStore.cs index 7f543ef18..d982e6aad 100644 --- a/Workshops/BuildYourOwnEventStore/02-CreateEventsTable/EventStore.cs +++ b/Workshops/BuildYourOwnEventStore/02-CreateEventsTable/EventStore.cs @@ -3,15 +3,8 @@ namespace EventStoreBasics; -public class EventStore: IDisposable, IEventStore +public class EventStore(NpgsqlConnection databaseConnection): IDisposable, IEventStore { - private readonly NpgsqlConnection databaseConnection; - - public EventStore(NpgsqlConnection databaseConnection) - { - this.databaseConnection = databaseConnection; - } - public void Init() { // See more in Greg Young's "Building an Event Storage" article https://cqrs.wordpress.com/documents/building-event-storage/ diff --git a/Workshops/BuildYourOwnEventStore/03-CreateAppendEventFunction/EventStore.cs b/Workshops/BuildYourOwnEventStore/03-CreateAppendEventFunction/EventStore.cs index e0fe3dff7..e6e9733ff 100644 --- a/Workshops/BuildYourOwnEventStore/03-CreateAppendEventFunction/EventStore.cs +++ b/Workshops/BuildYourOwnEventStore/03-CreateAppendEventFunction/EventStore.cs @@ -4,15 +4,8 @@ namespace EventStoreBasics; -public class EventStore: IDisposable, IEventStore +public class EventStore(NpgsqlConnection databaseConnection): IDisposable, IEventStore { - private readonly NpgsqlConnection databaseConnection; - - public EventStore(NpgsqlConnection databaseConnection) - { - this.databaseConnection = databaseConnection; - } - public void Init() { // See more in Greg Young's "Building an Event Storage" article https://cqrs.wordpress.com/documents/building-event-storage/ @@ -111,4 +104,4 @@ public void Dispose() { databaseConnection.Dispose(); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/03-OptimisticConcurrency/EventStore.cs b/Workshops/BuildYourOwnEventStore/03-OptimisticConcurrency/EventStore.cs index 224a2f6fc..20cc243ef 100644 --- a/Workshops/BuildYourOwnEventStore/03-OptimisticConcurrency/EventStore.cs +++ b/Workshops/BuildYourOwnEventStore/03-OptimisticConcurrency/EventStore.cs @@ -4,15 +4,8 @@ namespace EventStoreBasics; -public class EventStore: IDisposable, IEventStore +public class EventStore(NpgsqlConnection databaseConnection): IDisposable, IEventStore { - private readonly NpgsqlConnection databaseConnection; - - public EventStore(NpgsqlConnection databaseConnection) - { - this.databaseConnection = databaseConnection; - } - public void Init() { // See more in Greg Young's "Building an Event Storage" article https://cqrs.wordpress.com/documents/building-event-storage/ @@ -114,4 +107,4 @@ public void Dispose() { databaseConnection.Dispose(); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/04-EventStoreMethods/EventStore.cs b/Workshops/BuildYourOwnEventStore/04-EventStoreMethods/EventStore.cs index c80f4301d..e0e514617 100644 --- a/Workshops/BuildYourOwnEventStore/04-EventStoreMethods/EventStore.cs +++ b/Workshops/BuildYourOwnEventStore/04-EventStoreMethods/EventStore.cs @@ -6,17 +6,10 @@ namespace EventStoreBasics; -public class EventStore: IDisposable, IEventStore +public class EventStore(NpgsqlConnection databaseConnection): IDisposable, IEventStore { - private readonly NpgsqlConnection databaseConnection; - private const string Apply = "Apply"; - public EventStore(NpgsqlConnection databaseConnection) - { - this.databaseConnection = databaseConnection; - } - public void Init() { // See more in Greg Young's "Building an Event Storage" article https://cqrs.wordpress.com/documents/building-event-storage/ @@ -135,4 +128,4 @@ public void Dispose() { databaseConnection.Dispose(); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/04-EventStoreMethods/StreamState.cs b/Workshops/BuildYourOwnEventStore/04-EventStoreMethods/StreamState.cs index cf6d71783..4ab82850d 100644 --- a/Workshops/BuildYourOwnEventStore/04-EventStoreMethods/StreamState.cs +++ b/Workshops/BuildYourOwnEventStore/04-EventStoreMethods/StreamState.cs @@ -1,17 +1,10 @@ namespace EventStoreBasics; -public class StreamState +public class StreamState(Guid id, Type type, long version) { - public Guid Id { get; } + public Guid Id { get; } = id; - public Type Type { get; } + public Type Type { get; } = type; - public long Version { get; } - - public StreamState(Guid id, Type type, long version) - { - Id = id; - Type = type; - Version = version; - } -} \ No newline at end of file + public long Version { get; } = version; +} diff --git a/Workshops/BuildYourOwnEventStore/05-StreamAggregation/EventStore.cs b/Workshops/BuildYourOwnEventStore/05-StreamAggregation/EventStore.cs index cf85922a0..d535e6e07 100644 --- a/Workshops/BuildYourOwnEventStore/05-StreamAggregation/EventStore.cs +++ b/Workshops/BuildYourOwnEventStore/05-StreamAggregation/EventStore.cs @@ -6,17 +6,10 @@ namespace EventStoreBasics; -public class EventStore: IDisposable, IEventStore +public class EventStore(NpgsqlConnection databaseConnection): IDisposable, IEventStore { - private readonly NpgsqlConnection databaseConnection; - private const string Apply = "Apply"; - public EventStore(NpgsqlConnection databaseConnection) - { - this.databaseConnection = databaseConnection; - } - public void Init() { // See more in Greg Young's "Building an Event Storage" article https://cqrs.wordpress.com/documents/building-event-storage/ @@ -170,4 +163,4 @@ public void Dispose() { databaseConnection.Dispose(); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/05-StreamAggregation/Exercise05StreamAggregation.cs b/Workshops/BuildYourOwnEventStore/05-StreamAggregation/Exercise05StreamAggregation.cs index 116f64f67..4b3b89b7b 100644 --- a/Workshops/BuildYourOwnEventStore/05-StreamAggregation/Exercise05StreamAggregation.cs +++ b/Workshops/BuildYourOwnEventStore/05-StreamAggregation/Exercise05StreamAggregation.cs @@ -34,28 +34,16 @@ public void Apply(UserNameUpdated @event) } } - public class UserCreated + public class UserCreated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserCreated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } - public class UserNameUpdated + public class UserNameUpdated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserNameUpdated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } private readonly NpgsqlConnection databaseConnection; diff --git a/Workshops/BuildYourOwnEventStore/05-StreamAggregation/StreamState.cs b/Workshops/BuildYourOwnEventStore/05-StreamAggregation/StreamState.cs index cf6d71783..4ab82850d 100644 --- a/Workshops/BuildYourOwnEventStore/05-StreamAggregation/StreamState.cs +++ b/Workshops/BuildYourOwnEventStore/05-StreamAggregation/StreamState.cs @@ -1,17 +1,10 @@ namespace EventStoreBasics; -public class StreamState +public class StreamState(Guid id, Type type, long version) { - public Guid Id { get; } + public Guid Id { get; } = id; - public Type Type { get; } + public Type Type { get; } = type; - public long Version { get; } - - public StreamState(Guid id, Type type, long version) - { - Id = id; - Type = type; - Version = version; - } -} \ No newline at end of file + public long Version { get; } = version; +} diff --git a/Workshops/BuildYourOwnEventStore/06-TimeTraveling/EventStore.cs b/Workshops/BuildYourOwnEventStore/06-TimeTraveling/EventStore.cs index cf3541ba2..e930ace25 100644 --- a/Workshops/BuildYourOwnEventStore/06-TimeTraveling/EventStore.cs +++ b/Workshops/BuildYourOwnEventStore/06-TimeTraveling/EventStore.cs @@ -7,18 +7,11 @@ namespace EventStoreBasics; -public class EventStore: IDisposable, IEventStore +public class EventStore(NpgsqlConnection databaseConnection): IDisposable, IEventStore { - private readonly NpgsqlConnection databaseConnection; - private const string Apply = "Apply"; private const string Version = "Version"; - public EventStore(NpgsqlConnection databaseConnection) - { - this.databaseConnection = databaseConnection; - } - public void Init() { // See more in Greg Young's "Building an Event Storage" article https://cqrs.wordpress.com/documents/building-event-storage/ @@ -180,4 +173,4 @@ public void Dispose() { databaseConnection.Dispose(); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/06-TimeTraveling/Exercise06TimeTraveling.cs b/Workshops/BuildYourOwnEventStore/06-TimeTraveling/Exercise06TimeTraveling.cs index 273289054..0e8e76bbc 100644 --- a/Workshops/BuildYourOwnEventStore/06-TimeTraveling/Exercise06TimeTraveling.cs +++ b/Workshops/BuildYourOwnEventStore/06-TimeTraveling/Exercise06TimeTraveling.cs @@ -34,28 +34,16 @@ public void Apply(UserNameUpdated @event) } } - public class UserCreated + public class UserCreated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserCreated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } - public class UserNameUpdated + public class UserNameUpdated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserNameUpdated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } private readonly NpgsqlConnection databaseConnection; diff --git a/Workshops/BuildYourOwnEventStore/06-TimeTraveling/StreamState.cs b/Workshops/BuildYourOwnEventStore/06-TimeTraveling/StreamState.cs index cf6d71783..4ab82850d 100644 --- a/Workshops/BuildYourOwnEventStore/06-TimeTraveling/StreamState.cs +++ b/Workshops/BuildYourOwnEventStore/06-TimeTraveling/StreamState.cs @@ -1,17 +1,10 @@ namespace EventStoreBasics; -public class StreamState +public class StreamState(Guid id, Type type, long version) { - public Guid Id { get; } + public Guid Id { get; } = id; - public Type Type { get; } + public Type Type { get; } = type; - public long Version { get; } - - public StreamState(Guid id, Type type, long version) - { - Id = id; - Type = type; - Version = version; - } -} \ No newline at end of file + public long Version { get; } = version; +} diff --git a/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/EventStore.cs b/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/EventStore.cs index 1db4dab3b..bac11e1d2 100644 --- a/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/EventStore.cs +++ b/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/EventStore.cs @@ -7,17 +7,10 @@ namespace EventStoreBasics; -public class EventStore: IDisposable, IEventStore +public class EventStore(NpgsqlConnection databaseConnection): IDisposable, IEventStore { - private readonly NpgsqlConnection databaseConnection; - private const string Apply = "Apply"; - public EventStore(NpgsqlConnection databaseConnection) - { - this.databaseConnection = databaseConnection; - } - public void Init() { // See more in Greg Young's "Building an Event Storage" article https://cqrs.wordpress.com/documents/building-event-storage/ @@ -188,4 +181,4 @@ public void Dispose() { databaseConnection.Dispose(); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/Exercise07AggregateAndRepository.cs b/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/Exercise07AggregateAndRepository.cs index ce2c2547b..3e1ebedb9 100644 --- a/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/Exercise07AggregateAndRepository.cs +++ b/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/Exercise07AggregateAndRepository.cs @@ -42,28 +42,16 @@ public void Apply(UserNameUpdated @event) } } - public class UserCreated + public class UserCreated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserCreated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } - public class UserNameUpdated + public class UserNameUpdated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserNameUpdated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } private readonly NpgsqlConnection databaseConnection; @@ -111,4 +99,4 @@ public void Repository_FullFlow_ShouldSucceed() userAfterUpdate.Name.Should().Be("Adam Smith"); userFromRepository.Version.Should().Be(2); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/Repository.cs b/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/Repository.cs index 3543d81db..b0783a353 100644 --- a/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/Repository.cs +++ b/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/Repository.cs @@ -1,13 +1,9 @@ namespace EventStoreBasics; -public class Repository: IRepository where T : IAggregate +public class Repository(IEventStore eventStore): IRepository + where T : IAggregate { - private readonly IEventStore eventStore; - - public Repository(IEventStore eventStore) - { - this.eventStore = eventStore ?? throw new ArgumentNullException(nameof(eventStore)); - } + private readonly IEventStore eventStore = eventStore ?? throw new ArgumentNullException(nameof(eventStore)); public T Find(Guid id) { @@ -28,4 +24,4 @@ public void Delete(T aggregate) { throw new NotImplementedException("Add delete event to stream"); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/StreamState.cs b/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/StreamState.cs index cf6d71783..4ab82850d 100644 --- a/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/StreamState.cs +++ b/Workshops/BuildYourOwnEventStore/07-AggregateAndRepository/StreamState.cs @@ -1,17 +1,10 @@ namespace EventStoreBasics; -public class StreamState +public class StreamState(Guid id, Type type, long version) { - public Guid Id { get; } + public Guid Id { get; } = id; - public Type Type { get; } + public Type Type { get; } = type; - public long Version { get; } - - public StreamState(Guid id, Type type, long version) - { - Id = id; - Type = type; - Version = version; - } -} \ No newline at end of file + public long Version { get; } = version; +} diff --git a/Workshops/BuildYourOwnEventStore/08-Snapshots/EventStore.cs b/Workshops/BuildYourOwnEventStore/08-Snapshots/EventStore.cs index 49754e8f7..289f7c702 100644 --- a/Workshops/BuildYourOwnEventStore/08-Snapshots/EventStore.cs +++ b/Workshops/BuildYourOwnEventStore/08-Snapshots/EventStore.cs @@ -7,19 +7,12 @@ namespace EventStoreBasics; -public class EventStore: IDisposable, IEventStore +public class EventStore(NpgsqlConnection databaseConnection): IDisposable, IEventStore { - private readonly NpgsqlConnection databaseConnection; - private readonly IList snapshots = new List(); private const string Apply = "Apply"; - public EventStore(NpgsqlConnection databaseConnection) - { - this.databaseConnection = databaseConnection; - } - public void Init() { // See more in Greg Young's "Building an Event Storage" article https://cqrs.wordpress.com/documents/building-event-storage/ diff --git a/Workshops/BuildYourOwnEventStore/08-Snapshots/Exercise08Snapshots.cs b/Workshops/BuildYourOwnEventStore/08-Snapshots/Exercise08Snapshots.cs index 55913d156..b12156fdd 100644 --- a/Workshops/BuildYourOwnEventStore/08-Snapshots/Exercise08Snapshots.cs +++ b/Workshops/BuildYourOwnEventStore/08-Snapshots/Exercise08Snapshots.cs @@ -47,28 +47,16 @@ public void Apply(UserNameUpdated @event) } } - public class UserCreated + public class UserCreated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserCreated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } - public class UserNameUpdated + public class UserNameUpdated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserNameUpdated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } [Migration(1, "Create Users table")] @@ -178,4 +166,4 @@ FROM USERS users.Should().Contain(UserEqualTo(secondMatchingUser)); users.Should().NotContain(UserEqualTo(notMatchingUser)); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/08-Snapshots/Repository.cs b/Workshops/BuildYourOwnEventStore/08-Snapshots/Repository.cs index 8dc3505ac..b8a58a9af 100644 --- a/Workshops/BuildYourOwnEventStore/08-Snapshots/Repository.cs +++ b/Workshops/BuildYourOwnEventStore/08-Snapshots/Repository.cs @@ -1,13 +1,9 @@ namespace EventStoreBasics; -public class Repository: IRepository where T: IAggregate +public class Repository(IEventStore eventStore): IRepository + where T : IAggregate { - private readonly IEventStore eventStore; - - public Repository(IEventStore eventStore) - { - this.eventStore = eventStore ?? throw new ArgumentNullException(nameof(eventStore)); - } + private readonly IEventStore eventStore = eventStore ?? throw new ArgumentNullException(nameof(eventStore)); public T Find(Guid id) { @@ -28,4 +24,4 @@ public void Delete(T aggregate) { eventStore.Store(aggregate); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/08-Snapshots/SnapshotToTable.cs b/Workshops/BuildYourOwnEventStore/08-Snapshots/SnapshotToTable.cs index 8df133d6e..936a370ab 100644 --- a/Workshops/BuildYourOwnEventStore/08-Snapshots/SnapshotToTable.cs +++ b/Workshops/BuildYourOwnEventStore/08-Snapshots/SnapshotToTable.cs @@ -2,16 +2,10 @@ namespace EventStoreBasics; -public class SnapshotToTable: ISnapshot +public class SnapshotToTable(NpgsqlConnection databaseConnection, string upsertSql): ISnapshot { - private readonly NpgsqlConnection databaseConnection; - private readonly string upsertSql; - - public SnapshotToTable(NpgsqlConnection databaseConnection, string upsertSql) - { - this.databaseConnection = databaseConnection; - this.upsertSql = upsertSql; - } + private readonly NpgsqlConnection databaseConnection = databaseConnection; + private readonly string upsertSql = upsertSql; public Type Handles => typeof(T); @@ -19,4 +13,4 @@ public void Handle(IAggregate aggregate) { throw new NotImplementedException("Call upsert statement"); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/08-Snapshots/StreamState.cs b/Workshops/BuildYourOwnEventStore/08-Snapshots/StreamState.cs index cf6d71783..4ab82850d 100644 --- a/Workshops/BuildYourOwnEventStore/08-Snapshots/StreamState.cs +++ b/Workshops/BuildYourOwnEventStore/08-Snapshots/StreamState.cs @@ -1,17 +1,10 @@ namespace EventStoreBasics; -public class StreamState +public class StreamState(Guid id, Type type, long version) { - public Guid Id { get; } + public Guid Id { get; } = id; - public Type Type { get; } + public Type Type { get; } = type; - public long Version { get; } - - public StreamState(Guid id, Type type, long version) - { - Id = id; - Type = type; - Version = version; - } -} \ No newline at end of file + public long Version { get; } = version; +} diff --git a/Workshops/BuildYourOwnEventStore/09-Projections/EventStore.cs b/Workshops/BuildYourOwnEventStore/09-Projections/EventStore.cs index 69374c2d8..3c6834fcd 100644 --- a/Workshops/BuildYourOwnEventStore/09-Projections/EventStore.cs +++ b/Workshops/BuildYourOwnEventStore/09-Projections/EventStore.cs @@ -7,20 +7,13 @@ namespace EventStoreBasics; -public class EventStore: IDisposable, IEventStore +public class EventStore(NpgsqlConnection databaseConnection): IDisposable, IEventStore { - private readonly NpgsqlConnection databaseConnection; - private readonly IList snapshots = new List(); private readonly IList projections = new List(); private const string Apply = "Apply"; - public EventStore(NpgsqlConnection databaseConnection) - { - this.databaseConnection = databaseConnection; - } - public void Init() { // See more in Greg Young's "Building an Event Storage" article https://cqrs.wordpress.com/documents/building-event-storage/ diff --git a/Workshops/BuildYourOwnEventStore/09-Projections/Exercise09Projections.cs b/Workshops/BuildYourOwnEventStore/09-Projections/Exercise09Projections.cs index 89858113b..24e5d5e2e 100644 --- a/Workshops/BuildYourOwnEventStore/09-Projections/Exercise09Projections.cs +++ b/Workshops/BuildYourOwnEventStore/09-Projections/Exercise09Projections.cs @@ -90,14 +90,9 @@ public record UserDashboard( decimal TotalAmount ); - public class UserDashboardProjection: Projection + public class UserDashboardProjection(NpgsqlConnection databaseConnection): Projection { - private readonly NpgsqlConnection databaseConnection; - - public UserDashboardProjection(NpgsqlConnection databaseConnection) - { - this.databaseConnection = databaseConnection; - } + private readonly NpgsqlConnection databaseConnection = databaseConnection; public void Apply(UserCreated @event) { @@ -187,4 +182,4 @@ public void AddingAndUpdatingAggregate_ShouldCreateAndUpdateSnapshotAccordingly( userDashboard.OrdersCount.Should().Be(2); userDashboard.TotalAmount.Should().Be(firstOrder.Amount + secondOrder.Amount); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/09-Projections/Repository.cs b/Workshops/BuildYourOwnEventStore/09-Projections/Repository.cs index 8dc3505ac..b8a58a9af 100644 --- a/Workshops/BuildYourOwnEventStore/09-Projections/Repository.cs +++ b/Workshops/BuildYourOwnEventStore/09-Projections/Repository.cs @@ -1,13 +1,9 @@ namespace EventStoreBasics; -public class Repository: IRepository where T: IAggregate +public class Repository(IEventStore eventStore): IRepository + where T : IAggregate { - private readonly IEventStore eventStore; - - public Repository(IEventStore eventStore) - { - this.eventStore = eventStore ?? throw new ArgumentNullException(nameof(eventStore)); - } + private readonly IEventStore eventStore = eventStore ?? throw new ArgumentNullException(nameof(eventStore)); public T Find(Guid id) { @@ -28,4 +24,4 @@ public void Delete(T aggregate) { eventStore.Store(aggregate); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/09-Projections/SnapshotToTable.cs b/Workshops/BuildYourOwnEventStore/09-Projections/SnapshotToTable.cs index 81bd9ece7..6256297af 100644 --- a/Workshops/BuildYourOwnEventStore/09-Projections/SnapshotToTable.cs +++ b/Workshops/BuildYourOwnEventStore/09-Projections/SnapshotToTable.cs @@ -3,21 +3,12 @@ namespace EventStoreBasics; -public class SnapshotToTable: ISnapshot +public class SnapshotToTable(NpgsqlConnection databaseConnection, string upsertSql): ISnapshot { - private readonly NpgsqlConnection databaseConnection; - private readonly string upsertSql; - - public SnapshotToTable(NpgsqlConnection databaseConnection, string upsertSql) - { - this.databaseConnection = databaseConnection; - this.upsertSql = upsertSql; - } - public Type Handles => typeof(T); public void Handle(IAggregate aggregate) { databaseConnection.Execute(upsertSql, aggregate); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/09-Projections/StreamState.cs b/Workshops/BuildYourOwnEventStore/09-Projections/StreamState.cs index cf6d71783..4ab82850d 100644 --- a/Workshops/BuildYourOwnEventStore/09-Projections/StreamState.cs +++ b/Workshops/BuildYourOwnEventStore/09-Projections/StreamState.cs @@ -1,17 +1,10 @@ namespace EventStoreBasics; -public class StreamState +public class StreamState(Guid id, Type type, long version) { - public Guid Id { get; } + public Guid Id { get; } = id; - public Type Type { get; } + public Type Type { get; } = type; - public long Version { get; } - - public StreamState(Guid id, Type type, long version) - { - Id = id; - Type = type; - Version = version; - } -} \ No newline at end of file + public long Version { get; } = version; +} diff --git a/Workshops/BuildYourOwnEventStore/10-ProjectionsWithMarten/Exercise10ProjectionsWithMarten.cs b/Workshops/BuildYourOwnEventStore/10-ProjectionsWithMarten/Exercise10ProjectionsWithMarten.cs index 408604e40..a98381083 100644 --- a/Workshops/BuildYourOwnEventStore/10-ProjectionsWithMarten/Exercise10ProjectionsWithMarten.cs +++ b/Workshops/BuildYourOwnEventStore/10-ProjectionsWithMarten/Exercise10ProjectionsWithMarten.cs @@ -44,28 +44,16 @@ public void Apply(UserNameUpdated @event) } } - public class UserCreated + public class UserCreated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserCreated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } - public class UserNameUpdated + public class UserNameUpdated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserNameUpdated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } public class Order: Aggregate @@ -93,20 +81,12 @@ public void Apply(OrderCreated @event) } } - public class OrderCreated + public class OrderCreated(Guid orderId, Guid userId, string number, decimal amount) { - public Guid OrderId { get; } - public Guid UserId { get; } - public string Number { get; } - public decimal Amount { get; } - - public OrderCreated(Guid orderId, Guid userId, string number, decimal amount) - { - OrderId = orderId; - UserId = userId; - Number = number; - Amount = amount; - } + public Guid OrderId { get; } = orderId; + public Guid UserId { get; } = userId; + public string Number { get; } = number; + public decimal Amount { get; } = amount; } public class UserDashboard diff --git a/Workshops/BuildYourOwnEventStore/10-ProjectionsWithMarten/MartenRepository.cs b/Workshops/BuildYourOwnEventStore/10-ProjectionsWithMarten/MartenRepository.cs index dfde51d18..695a1cfb4 100644 --- a/Workshops/BuildYourOwnEventStore/10-ProjectionsWithMarten/MartenRepository.cs +++ b/Workshops/BuildYourOwnEventStore/10-ProjectionsWithMarten/MartenRepository.cs @@ -2,14 +2,10 @@ namespace EventStoreBasics; -public class MartenRepository: IRepository where T : class, IAggregate, new() +public class MartenRepository(IDocumentSession documentSession): IRepository + where T : class, IAggregate, new() { - private readonly IDocumentSession documentSession; - - public MartenRepository(IDocumentSession documentSession) - { - this.documentSession = documentSession ?? throw new ArgumentNullException(nameof(documentSession)); - } + private readonly IDocumentSession documentSession = documentSession ?? throw new ArgumentNullException(nameof(documentSession)); public T? Find(Guid id) { @@ -44,4 +40,4 @@ public void Delete(T aggregate) ); documentSession.SaveChanges(); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/10-ProjectionsWithMarten/StreamState.cs b/Workshops/BuildYourOwnEventStore/10-ProjectionsWithMarten/StreamState.cs index cf6d71783..4ab82850d 100644 --- a/Workshops/BuildYourOwnEventStore/10-ProjectionsWithMarten/StreamState.cs +++ b/Workshops/BuildYourOwnEventStore/10-ProjectionsWithMarten/StreamState.cs @@ -1,17 +1,10 @@ namespace EventStoreBasics; -public class StreamState +public class StreamState(Guid id, Type type, long version) { - public Guid Id { get; } + public Guid Id { get; } = id; - public Type Type { get; } + public Type Type { get; } = type; - public long Version { get; } - - public StreamState(Guid id, Type type, long version) - { - Id = id; - Type = type; - Version = version; - } -} \ No newline at end of file + public long Version { get; } = version; +} diff --git a/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise05StreamAggregation.cs b/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise05StreamAggregation.cs index 0ce08008b..eb2869320 100644 --- a/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise05StreamAggregation.cs +++ b/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise05StreamAggregation.cs @@ -34,29 +34,17 @@ public void Apply(UserNameUpdated @event) } } - class UserCreated + class UserCreated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserCreated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } - class UserNameUpdated + class UserNameUpdated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserNameUpdated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } private readonly NpgsqlConnection databaseConnection; @@ -92,4 +80,4 @@ public void AggregateStream_ShouldReturnObjectWithStateBasedOnEvents() aggregate.Name.Should().Be(userNameUpdated.UserName); aggregate.Version.Should().Be(2); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise06TimeTraveling.cs b/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise06TimeTraveling.cs index 6237aec25..b2822736e 100644 --- a/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise06TimeTraveling.cs +++ b/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise06TimeTraveling.cs @@ -34,29 +34,17 @@ public void Apply(UserNameUpdated @event) } } - class UserCreated + class UserCreated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserCreated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } - class UserNameUpdated + class UserNameUpdated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserNameUpdated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } private readonly NpgsqlConnection databaseConnection; @@ -108,4 +96,4 @@ public void AggregateStream_ShouldReturnSpecifiedVersionOfTheStream() aggregateAtVersion3.Name.Should().Be(userNameUpdatedAgain.UserName); aggregateAtVersion3.Version.Should().Be(3); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise07AggregateAndRepository.cs b/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise07AggregateAndRepository.cs index c590532ca..20c2ff6f1 100644 --- a/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise07AggregateAndRepository.cs +++ b/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise07AggregateAndRepository.cs @@ -43,29 +43,17 @@ public void Apply(UserNameUpdated @event) } } - class UserCreated + class UserCreated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserCreated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } - class UserNameUpdated + class UserNameUpdated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserNameUpdated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } private readonly NpgsqlConnection databaseConnection; @@ -112,4 +100,4 @@ public void Repository_FullFlow_ShouldSucceed() userAfterUpdate.Name.Should().Be("Adam Smith"); userFromRepository.Version.Should().Be(2); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise08Snapshots.cs b/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise08Snapshots.cs index ae7c72061..cee260808 100644 --- a/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise08Snapshots.cs +++ b/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise08Snapshots.cs @@ -47,29 +47,17 @@ public void Apply(UserNameUpdated @event) } } - class UserCreated + class UserCreated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserCreated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } - class UserNameUpdated + class UserNameUpdated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserNameUpdated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } [Migration(1, "Create Users table")] @@ -186,4 +174,4 @@ FROM USERS users.Should().Contain(UserEqualTo(secondMatchingUser)); users.Should().NotContain(UserEqualTo(notMatchingUser)); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise09Projections.cs b/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise09Projections.cs index 6750f2651..fa597c04b 100644 --- a/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise09Projections.cs +++ b/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise09Projections.cs @@ -46,29 +46,17 @@ public void Apply(UserNameUpdated @event) } } - class UserCreated + class UserCreated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserCreated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } - class UserNameUpdated + class UserNameUpdated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserNameUpdated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } class Order : Aggregate @@ -96,37 +84,21 @@ public void Apply(OrderCreated @event) } } - public class OrderCreated + public class OrderCreated(Guid orderId, Guid userId, string number, decimal amount) { - public Guid OrderId { get; } - public Guid UserId { get; } - public string Number { get; } - public decimal Amount { get; } - - public OrderCreated(Guid orderId, Guid userId, string number, decimal amount) - { - OrderId = orderId; - UserId = userId; - Number = number; - Amount = amount; - } + public Guid OrderId { get; } = orderId; + public Guid UserId { get; } = userId; + public string Number { get; } = number; + public decimal Amount { get; } = amount; } - public class UserDashboard + public class UserDashboard(Guid id, string userName, int ordersCount, decimal totalAmount) { - public Guid Id { get; } - public string UserName { get; } - public int OrdersCount { get; } - public decimal TotalAmount { get; } - - public UserDashboard(Guid id, string userName, int ordersCount, decimal totalAmount) - { - Id = id; - UserName = userName; - OrdersCount = ordersCount; - TotalAmount = totalAmount; - } + public Guid Id { get; } = id; + public string UserName { get; } = userName; + public int OrdersCount { get; } = ordersCount; + public decimal TotalAmount { get; } = totalAmount; } public class UserDashboardProjection : Projection @@ -249,4 +221,4 @@ public void AddingAndUpdatingAggregate_ShouldCreateAndUpdateSnapshotAccordingly( userDashboard.OrdersCount.Should().Be(2); userDashboard.TotalAmount.Should().Be(firstOrder.Amount + secondOrder.Amount); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise10ProjectionsWithMarten.cs b/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise10ProjectionsWithMarten.cs index 18b69f774..c77ad3933 100644 --- a/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise10ProjectionsWithMarten.cs +++ b/Workshops/BuildYourOwnEventStore/EventStoreBasics.Tests/Exercise10ProjectionsWithMarten.cs @@ -42,28 +42,16 @@ public void Apply(UserNameUpdated @event) } } -public class UserCreated +public class UserCreated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserCreated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } -public class UserNameUpdated +public class UserNameUpdated(Guid userId, string userName) { - public Guid UserId { get; } - public string UserName { get; } - - public UserNameUpdated(Guid userId, string userName) - { - UserId = userId; - UserName = userName; - } + public Guid UserId { get; } = userId; + public string UserName { get; } = userName; } public class Order: Aggregate @@ -91,20 +79,12 @@ public void Apply(OrderCreated @event) } } -public class OrderCreated +public class OrderCreated(Guid orderId, Guid userId, string number, decimal amount) { - public Guid OrderId { get; } - public Guid UserId { get; } - public string Number { get; } - public decimal Amount { get; } - - public OrderCreated(Guid orderId, Guid userId, string number, decimal amount) - { - OrderId = orderId; - UserId = userId; - Number = number; - Amount = amount; - } + public Guid OrderId { get; } = orderId; + public Guid UserId { get; } = userId; + public string Number { get; } = number; + public decimal Amount { get; } = amount; } public class UserDashboard diff --git a/Workshops/BuildYourOwnEventStore/EventStoreBasics/EventStore.cs b/Workshops/BuildYourOwnEventStore/EventStoreBasics/EventStore.cs index 8bbbfd607..1b0b4c650 100644 --- a/Workshops/BuildYourOwnEventStore/EventStoreBasics/EventStore.cs +++ b/Workshops/BuildYourOwnEventStore/EventStoreBasics/EventStore.cs @@ -7,20 +7,13 @@ namespace EventStoreBasics; -public class EventStore: IDisposable, IEventStore +public class EventStore(NpgsqlConnection databaseConnection): IDisposable, IEventStore { - private readonly NpgsqlConnection databaseConnection; - private readonly IList snapshots = new List(); private readonly IList projections = new List(); private const string Apply = "Apply"; - public EventStore(NpgsqlConnection databaseConnection) - { - this.databaseConnection = databaseConnection; - } - public void Init() { // See more in Greg Young's "Building an Event Storage" article https://cqrs.wordpress.com/documents/building-event-storage/ @@ -221,4 +214,4 @@ public void Dispose() { databaseConnection.Dispose(); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/EventStoreBasics/MartenRepository.cs b/Workshops/BuildYourOwnEventStore/EventStoreBasics/MartenRepository.cs index fa24be4d8..21876ca12 100644 --- a/Workshops/BuildYourOwnEventStore/EventStoreBasics/MartenRepository.cs +++ b/Workshops/BuildYourOwnEventStore/EventStoreBasics/MartenRepository.cs @@ -2,14 +2,10 @@ namespace EventStoreBasics; -public class MartenRepository: IRepository where T : class, IAggregate, new() +public class MartenRepository(IDocumentSession documentSession): IRepository + where T : class, IAggregate, new() { - private readonly IDocumentSession documentSession; - - public MartenRepository(IDocumentSession documentSession) - { - this.documentSession = documentSession ?? throw new ArgumentNullException(nameof(documentSession)); - } + private readonly IDocumentSession documentSession = documentSession ?? throw new ArgumentNullException(nameof(documentSession)); public T Find(Guid id) { @@ -49,4 +45,4 @@ public void Delete(T aggregate) ); documentSession.SaveChanges(); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/EventStoreBasics/Repository.cs b/Workshops/BuildYourOwnEventStore/EventStoreBasics/Repository.cs index 8dc3505ac..b8a58a9af 100644 --- a/Workshops/BuildYourOwnEventStore/EventStoreBasics/Repository.cs +++ b/Workshops/BuildYourOwnEventStore/EventStoreBasics/Repository.cs @@ -1,13 +1,9 @@ namespace EventStoreBasics; -public class Repository: IRepository where T: IAggregate +public class Repository(IEventStore eventStore): IRepository + where T : IAggregate { - private readonly IEventStore eventStore; - - public Repository(IEventStore eventStore) - { - this.eventStore = eventStore ?? throw new ArgumentNullException(nameof(eventStore)); - } + private readonly IEventStore eventStore = eventStore ?? throw new ArgumentNullException(nameof(eventStore)); public T Find(Guid id) { @@ -28,4 +24,4 @@ public void Delete(T aggregate) { eventStore.Store(aggregate); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/EventStoreBasics/SnapshotToTable.cs b/Workshops/BuildYourOwnEventStore/EventStoreBasics/SnapshotToTable.cs index 81bd9ece7..6256297af 100644 --- a/Workshops/BuildYourOwnEventStore/EventStoreBasics/SnapshotToTable.cs +++ b/Workshops/BuildYourOwnEventStore/EventStoreBasics/SnapshotToTable.cs @@ -3,21 +3,12 @@ namespace EventStoreBasics; -public class SnapshotToTable: ISnapshot +public class SnapshotToTable(NpgsqlConnection databaseConnection, string upsertSql): ISnapshot { - private readonly NpgsqlConnection databaseConnection; - private readonly string upsertSql; - - public SnapshotToTable(NpgsqlConnection databaseConnection, string upsertSql) - { - this.databaseConnection = databaseConnection; - this.upsertSql = upsertSql; - } - public Type Handles => typeof(T); public void Handle(IAggregate aggregate) { databaseConnection.Execute(upsertSql, aggregate); } -} \ No newline at end of file +} diff --git a/Workshops/BuildYourOwnEventStore/EventStoreBasics/StreamState.cs b/Workshops/BuildYourOwnEventStore/EventStoreBasics/StreamState.cs index cf6d71783..4ab82850d 100644 --- a/Workshops/BuildYourOwnEventStore/EventStoreBasics/StreamState.cs +++ b/Workshops/BuildYourOwnEventStore/EventStoreBasics/StreamState.cs @@ -1,17 +1,10 @@ namespace EventStoreBasics; -public class StreamState +public class StreamState(Guid id, Type type, long version) { - public Guid Id { get; } + public Guid Id { get; } = id; - public Type Type { get; } + public Type Type { get; } = type; - public long Version { get; } - - public StreamState(Guid id, Type type, long version) - { - Id = id; - Type = type; - Version = version; - } -} \ No newline at end of file + public long Version { get; } = version; +} diff --git a/Workshops/BuildYourOwnEventStore/Tools/Tools/PostgresSchemaProvider.cs b/Workshops/BuildYourOwnEventStore/Tools/Tools/PostgresSchemaProvider.cs index 0b3658892..b23145064 100644 --- a/Workshops/BuildYourOwnEventStore/Tools/Tools/PostgresSchemaProvider.cs +++ b/Workshops/BuildYourOwnEventStore/Tools/Tools/PostgresSchemaProvider.cs @@ -6,10 +6,8 @@ namespace Tools.Tools; /// /// Helper class that returns information about the database schema (Tables and its Columns) /// -public class PostgresSchemaProvider +public class PostgresSchemaProvider(NpgsqlConnection databaseConnection) { - private readonly NpgsqlConnection databaseConnection; - const string GetTableColumnsSql = @"SELECT column_name AS name, data_type AS type FROM INFORMATION_SCHEMA.COLUMNS @@ -21,11 +19,6 @@ FROM INFORMATION_SCHEMA.COLUMNS private const string FunctionExistsSql = @"select exists(select * from pg_proc where proname = @functionName);"; - public PostgresSchemaProvider(NpgsqlConnection databaseConnection) - { - this.databaseConnection = databaseConnection; - } - /// /// Returns schema information about specific table /// @@ -52,22 +45,17 @@ public bool FunctionExists(string functionName) /// /// Describes basic information about database table /// -public class Table +public class Table(string name, IEnumerable columns) { /// /// Table Name /// - public string Name { get; } + public string Name { get; } = name; + /// /// Table Columns /// - private IEnumerable Columns { get; } - - public Table(string name, IEnumerable columns) - { - Name = name; - Columns = columns; - } + private IEnumerable Columns { get; } = columns; public Column? GetColumn(string columnName) { @@ -78,7 +66,7 @@ public Table(string name, IEnumerable columns) /// /// Describes basic information about database column /// -public class Column +public class Column(string name, string type) { public const string GuidType = "uuid"; public const string LongType = "bigint"; @@ -89,16 +77,10 @@ public class Column /// /// Column Name /// - public string Name { get; } + public string Name { get; } = name; + /// /// Column Type /// - public string Type { get; } - - - public Column(string name, string type) - { - Name = name; - Type = type; - } -} \ No newline at end of file + public string Type { get; } = type; +} diff --git a/Workshops/IntroductionToEventSourcing/06-GettingStateFromEvents.EventStoreDB/Tools/EventStoreDBTest.cs b/Workshops/IntroductionToEventSourcing/06-GettingStateFromEvents.EventStoreDB/Tools/EventStoreDBTest.cs index 930e298b0..dab7924c8 100644 --- a/Workshops/IntroductionToEventSourcing/06-GettingStateFromEvents.EventStoreDB/Tools/EventStoreDBTest.cs +++ b/Workshops/IntroductionToEventSourcing/06-GettingStateFromEvents.EventStoreDB/Tools/EventStoreDBTest.cs @@ -5,13 +5,7 @@ namespace IntroductionToEventSourcing.GettingStateFromEvents.Tools; public abstract class EventStoreDBTest: IDisposable { - protected readonly EventStoreClient EventStore; - - protected EventStoreDBTest() - { - EventStore = - new EventStoreClient(EventStoreClientSettings.Create("esdb://localhost:2113?tls=false")); - } + protected readonly EventStoreClient EventStore = new(EventStoreClientSettings.Create("esdb://localhost:2113?tls=false")); protected Task AppendEvents(string streamName, IEnumerable events, CancellationToken ct) { diff --git a/Workshops/IntroductionToEventSourcing/13-Projections.SingleStream.Idempotency/ProjectionsTests.cs b/Workshops/IntroductionToEventSourcing/13-Projections.SingleStream.Idempotency/ProjectionsTests.cs index 3b3633c47..0050a151d 100644 --- a/Workshops/IntroductionToEventSourcing/13-Projections.SingleStream.Idempotency/ProjectionsTests.cs +++ b/Workshops/IntroductionToEventSourcing/13-Projections.SingleStream.Idempotency/ProjectionsTests.cs @@ -77,11 +77,8 @@ public static void GetAndStore(this Database database, Guid id, Func up } } -public class ShoppingCartDetailsProjection +public class ShoppingCartDetailsProjection(Database database) { - private readonly Database database; - public ShoppingCartDetailsProjection(Database database) => this.database = database; - public void Handle(EventEnvelope @event) => database.Store(@event.Data.ShoppingCartId, new ShoppingCartDetails @@ -174,12 +171,8 @@ public class ShoppingCartDetailsProjection }); } -public class ShoppingCartShortInfoProjection +public class ShoppingCartShortInfoProjection(Database database) { - private readonly Database database; - - public ShoppingCartShortInfoProjection(Database database) => this.database = database; - public void Handle(EventEnvelope @event) => database.Store(@event.Data.ShoppingCartId, new ShoppingCartShortInfo diff --git a/Workshops/IntroductionToEventSourcing/14-Projections.SingleStream.EventualConsistency/ProjectionsTests.cs b/Workshops/IntroductionToEventSourcing/14-Projections.SingleStream.EventualConsistency/ProjectionsTests.cs index 8be9af72b..b08f79eeb 100644 --- a/Workshops/IntroductionToEventSourcing/14-Projections.SingleStream.EventualConsistency/ProjectionsTests.cs +++ b/Workshops/IntroductionToEventSourcing/14-Projections.SingleStream.EventualConsistency/ProjectionsTests.cs @@ -77,11 +77,8 @@ public static void GetAndStore(this Database database, Guid id, Func up } } -public class ShoppingCartDetailsProjection +public class ShoppingCartDetailsProjection(Database database) { - private readonly Database database; - public ShoppingCartDetailsProjection(Database database) => this.database = database; - public void Handle(EventEnvelope @event) => database.Store(@event.Data.ShoppingCartId, new ShoppingCartDetails @@ -174,12 +171,8 @@ public class ShoppingCartDetailsProjection }); } -public class ShoppingCartShortInfoProjection +public class ShoppingCartShortInfoProjection(Database database) { - private readonly Database database; - - public ShoppingCartShortInfoProjection(Database database) => this.database = database; - public void Handle(EventEnvelope @event) => database.Store(@event.Data.ShoppingCartId, new ShoppingCartShortInfo diff --git a/Workshops/IntroductionToEventSourcing/Solved/06-GettingStateFromEvents.EventStoreDB/Tools/EventStoreDBTest.cs b/Workshops/IntroductionToEventSourcing/Solved/06-GettingStateFromEvents.EventStoreDB/Tools/EventStoreDBTest.cs index 930e298b0..dab7924c8 100644 --- a/Workshops/IntroductionToEventSourcing/Solved/06-GettingStateFromEvents.EventStoreDB/Tools/EventStoreDBTest.cs +++ b/Workshops/IntroductionToEventSourcing/Solved/06-GettingStateFromEvents.EventStoreDB/Tools/EventStoreDBTest.cs @@ -5,13 +5,7 @@ namespace IntroductionToEventSourcing.GettingStateFromEvents.Tools; public abstract class EventStoreDBTest: IDisposable { - protected readonly EventStoreClient EventStore; - - protected EventStoreDBTest() - { - EventStore = - new EventStoreClient(EventStoreClientSettings.Create("esdb://localhost:2113?tls=false")); - } + protected readonly EventStoreClient EventStore = new(EventStoreClientSettings.Create("esdb://localhost:2113?tls=false")); protected Task AppendEvents(string streamName, IEnumerable events, CancellationToken ct) { diff --git a/Workshops/IntroductionToEventSourcing/Solved/12-Projections.SingleStream/ProjectionsTests.cs b/Workshops/IntroductionToEventSourcing/Solved/12-Projections.SingleStream/ProjectionsTests.cs index 1de18967d..d2ded4fa2 100644 --- a/Workshops/IntroductionToEventSourcing/Solved/12-Projections.SingleStream/ProjectionsTests.cs +++ b/Workshops/IntroductionToEventSourcing/Solved/12-Projections.SingleStream/ProjectionsTests.cs @@ -77,11 +77,8 @@ public static void GetAndStore(this Database database, Guid id, Func up } } -public class ShoppingCartDetailsProjection +public class ShoppingCartDetailsProjection(Database database) { - private readonly Database database; - public ShoppingCartDetailsProjection(Database database) => this.database = database; - public void Handle(EventEnvelope @event) => database.Store(@event.Data.ShoppingCartId, new ShoppingCartDetails @@ -174,12 +171,8 @@ public class ShoppingCartDetailsProjection }); } -public class ShoppingCartShortInfoProjection +public class ShoppingCartShortInfoProjection(Database database) { - private readonly Database database; - - public ShoppingCartShortInfoProjection(Database database) => this.database = database; - public void Handle(EventEnvelope @event) => database.Store(@event.Data.ShoppingCartId, new ShoppingCartShortInfo diff --git a/Workshops/IntroductionToEventSourcing/Solved/13-Projections.SingleStream.Idempotency/ProjectionsTests.cs b/Workshops/IntroductionToEventSourcing/Solved/13-Projections.SingleStream.Idempotency/ProjectionsTests.cs index ecdf64647..06efb461b 100644 --- a/Workshops/IntroductionToEventSourcing/Solved/13-Projections.SingleStream.Idempotency/ProjectionsTests.cs +++ b/Workshops/IntroductionToEventSourcing/Solved/13-Projections.SingleStream.Idempotency/ProjectionsTests.cs @@ -91,11 +91,8 @@ public static void GetAndStore(this Database database, Guid id, ulong version } } -public class ShoppingCartDetailsProjection +public class ShoppingCartDetailsProjection(Database database) { - private readonly Database database; - public ShoppingCartDetailsProjection(Database database) => this.database = database; - public void Handle(EventEnvelope @event) => database.Store( @event.Data.ShoppingCartId, @@ -202,12 +199,8 @@ public class ShoppingCartDetailsProjection }); } -public class ShoppingCartShortInfoProjection +public class ShoppingCartShortInfoProjection(Database database) { - private readonly Database database; - - public ShoppingCartShortInfoProjection(Database database) => this.database = database; - public void Handle(EventEnvelope @event) => database.Store( @event.Data.ShoppingCartId, diff --git a/Workshops/IntroductionToEventSourcing/Solved/14-Projections.SingleStream.EventualConsistency/ProjectionsTests.cs b/Workshops/IntroductionToEventSourcing/Solved/14-Projections.SingleStream.EventualConsistency/ProjectionsTests.cs index 68c13dc5a..ffe0c107f 100644 --- a/Workshops/IntroductionToEventSourcing/Solved/14-Projections.SingleStream.EventualConsistency/ProjectionsTests.cs +++ b/Workshops/IntroductionToEventSourcing/Solved/14-Projections.SingleStream.EventualConsistency/ProjectionsTests.cs @@ -118,11 +118,8 @@ public static void GetAndStore(this Database database, Guid id, ulong current } } -public class ShoppingCartDetailsProjection +public class ShoppingCartDetailsProjection(Database database) { - private readonly Database database; - public ShoppingCartDetailsProjection(Database database) => this.database = database; - public void Handle(EventEnvelope @event) => database.Store( @event.Data.ShoppingCartId, @@ -229,12 +226,8 @@ public class ShoppingCartDetailsProjection }); } -public class ShoppingCartShortInfoProjection +public class ShoppingCartShortInfoProjection(Database database) { - private readonly Database database; - - public ShoppingCartShortInfoProjection(Database database) => this.database = database; - public void Handle(EventEnvelope @event) => database.Store( @event.Data.ShoppingCartId,