Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using KSFramework.KSMessaging.Abstraction;
using Microsoft.Extensions.Logging;
using Project.Domain.Aggregates.Blog.Events;

namespace Project.Application.Blog.EventHandlers;

public sealed class PostCreatedDomainEventHandler : INotificationHandler<PostCreatedDomainEvent>
{
private readonly ILogger<PostCreatedDomainEventHandler> _logger;

public PostCreatedDomainEventHandler(ILogger<PostCreatedDomainEventHandler> logger)
{
_logger = logger;
}

public Task Handle(PostCreatedDomainEvent notification, CancellationToken cancellationToken)
{
_logger.LogInformation("Post created: {PostId} - {Title}", notification.PostId, notification.Title);

// Here you can add additional business logic like:
// - Sending notifications
// - Updating read models
// - Triggering external systems

return Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
Expand Down
5 changes: 2 additions & 3 deletions Samples/BlogApp/Project.ClientApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,11 @@

app.UseAuthorization();

app.MapStaticAssets();
app.UseStaticFiles();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}")
.WithStaticAssets();
pattern: "{controller=Home}/{action=Index}/{id?}");


app.Run();
2 changes: 1 addition & 1 deletion Samples/BlogApp/Project.ClientApp/Project.ClientApp.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
Expand Down
4 changes: 2 additions & 2 deletions Samples/BlogApp/Project.Common/Project.Common.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using KSFramework.KSDomain;

namespace Project.Domain.Aggregates.Blog.Events;

public sealed class PostCreatedDomainEvent : IDomainEvent
{
public PostCreatedDomainEvent(Guid postId, string title)
{
PostId = postId;
Title = title;
OccurredOn = DateTime.UtcNow;
}

public Guid PostId { get; }
public string Title { get; }
public DateTime OccurredOn { get; }
}
2 changes: 2 additions & 0 deletions Samples/BlogApp/Project.Domain/Aggregates/Blog/Post.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using KSFramework.Utilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Project.Domain.Aggregates.Blog.Events;

namespace Project.Domain.Aggregates.Blog;

Expand Down Expand Up @@ -44,6 +45,7 @@ public static Post Create(string title, string content)
Id = Guid.NewGuid(),
};

post.AddDomainEvent(new PostCreatedDomainEvent(post.Id, post.Title));
return post;
}

Expand Down
4 changes: 2 additions & 2 deletions Samples/BlogApp/Project.Domain/Project.Domain.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,24 @@
using KSFramework.Utilities;
using Microsoft.EntityFrameworkCore;
using Project.Infrastructure.Outbox;
using Microsoft.Extensions.DependencyInjection;
using Project.Infrastructure.Services;
using System.Linq;

namespace Project.Infrastructure.Data;

public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
:base(options)
private readonly IDomainEventDispatcher _dispatcher;
private readonly IServiceProvider _serviceProvider;

public ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options,
IServiceProvider serviceProvider)
: base(options)
{
_serviceProvider = serviceProvider;
_dispatcher = _serviceProvider.GetRequiredService<IDomainEventDispatcher>();
}

public DbSet<OutboxMessage> OutboxMessages { get; set; }
Expand Down Expand Up @@ -48,4 +58,26 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)

#endregion
}

public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
var domainEvents = ChangeTracker.Entries<BaseEntity>()
.SelectMany(x => x.Entity.DomainEvents)
.ToList();

var result = await base.SaveChangesAsync(cancellationToken);

if (domainEvents.Any())
{
await _dispatcher.DispatchEventsAsync(domainEvents, cancellationToken);

// Clear domain events after dispatching
foreach (var entry in ChangeTracker.Entries<BaseEntity>())
{
entry.Entity.ClearDomainEvents();
}
}

return result;
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using KSFramework.GenericRepository;
using KSFramework.GenericRepository;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
Expand All @@ -18,6 +18,8 @@ public static IServiceCollection RegisterInfrastructure(this IServiceCollection
x =>
x.MigrationsAssembly("Project.Infrastructure"));
});

services.AddScoped<KSFramework.KSDomain.IDomainEventDispatcher, KSFramework.KSDomain.DomainEventDispatcher>();
services.AddScoped<DbContext, ApplicationDbContext>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
return services;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\src\KSFramework\KSFramework.csproj" />
<ProjectReference Include="..\Project.Common\Project.Common.csproj" />
<ProjectReference Include="..\Project.Domain\Project.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Project.Domain\Project.Domain.csproj" />
<ProjectReference Include="..\..\..\src\KSFramework\KSFramework.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using KSFramework.KSDomain;
using KSFramework.KSMessaging.Abstraction;
using Microsoft.Extensions.DependencyInjection;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System;

namespace Project.Infrastructure.Services;

public sealed class DomainEventDispatcher : IDomainEventDispatcher
{
private readonly IServiceProvider _serviceProvider;

public DomainEventDispatcher(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}

public async Task DispatchEventsAsync(IEnumerable<IDomainEvent> domainEvents, CancellationToken cancellationToken = default)
{
foreach (var domainEvent in domainEvents)
{
var handlerType = typeof(INotificationHandler<>).MakeGenericType(domainEvent.GetType());

using var scope = _serviceProvider.CreateScope();
var handlers = scope.ServiceProvider.GetServices(handlerType);

foreach (var handler in handlers)
{
await (Task)handlerType
.GetMethod("Handle")
?.Invoke(handler, new object[] { domainEvent, cancellationToken })!;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
Expand Down
4 changes: 2 additions & 2 deletions Samples/BlogApp/Project.WebApi/Project.WebApi.csproj
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.5" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down
4 changes: 2 additions & 2 deletions Samples/BlogApp/Project.WebApi/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"ConnectionStrings":
{
"Default": "Server=localhost,1433;Initial Catalog=TestKSFrameworkBlogDb;User ID=sa;Password=SqlPassword123;TrustServerCertificate=true",
"Master": "Server=localhost,1433;Initial Catalog=Master;User ID=sa;Password=SqlPassword123;TrustServerCertificate=true"
"Default": "Server=localhost,1433;Initial Catalog=TestKSFrameworkBlogDb;User ID=sa;Password=reallyStrongPwd123;TrustServerCertificate=true",
"Master": "Server=localhost,1433;Initial Catalog=Master;User ID=sa;Password=reallyStrongPwd123;TrustServerCertificate=true"
},
"Logging": {
"LogLevel": {
Expand Down
36 changes: 36 additions & 0 deletions src/KSFramework/KSDomain/DomainEventDispatcher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using KSFramework.KSMessaging.Abstraction;
using Microsoft.Extensions.DependencyInjection;

namespace KSFramework.KSDomain;

public sealed class DomainEventDispatcher : IDomainEventDispatcher
{
private readonly IServiceProvider _serviceProvider;

public DomainEventDispatcher(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}

public async Task DispatchEventsAsync(IEnumerable<IDomainEvent> domainEvents, CancellationToken cancellationToken = default)
{
foreach (var domainEvent in domainEvents)
{
var handlerType = typeof(INotificationHandler<>).MakeGenericType(domainEvent.GetType());

using var scope = _serviceProvider.CreateScope();
var handlers = scope.ServiceProvider.GetServices(handlerType);

foreach (var handler in handlers)
{
await (Task)handlerType
.GetMethod("Handle")
?.Invoke(handler, new object[] { domainEvent, cancellationToken })!;
}
}
}
}
6 changes: 6 additions & 0 deletions src/KSFramework/KSDomain/IDomainEventDispatcher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace KSFramework.KSDomain;

public interface IDomainEventDispatcher
{
Task DispatchEventsAsync(IEnumerable<IDomainEvent> domainEvents, CancellationToken cancellationToken = default);
}