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
Expand Up @@ -14,6 +14,8 @@ public static class DependencyInjectionExtensions
/// <returns>The dependency container.</returns>
public static IServiceCollection AddLogitarEventSourcingInfrastructure(this IServiceCollection services)
{
return services.AddSingleton<IEventSerializer, EventSerializer>();
return services
.AddSingleton<IEventSerializer, EventSerializer>()
.AddScoped<IEventBus, EventBus>();
}
}
51 changes: 51 additions & 0 deletions lib/Logitar.EventSourcing.Infrastructure/EventBus.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace Logitar.EventSourcing.Infrastructure;

/// <summary>
/// Implements an in-memory event bus into which published events are handled synchronously.
/// </summary>
public class EventBus : IEventBus
{
/// <summary>
/// Gets the service provider.
/// </summary>
protected IServiceProvider ServiceProvider { get; }

/// <summary>
/// Initializes a new instance of the <see cref="EventBus"/> class.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
public EventBus(IServiceProvider serviceProvider)
{
ServiceProvider = serviceProvider;
}

/// <summary>
/// Publishes the specified event to the event bus.
/// </summary>
/// <param name="event">The event to publish.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The asynchronous operation.</returns>
public async Task PublishAsync(IEvent @event, CancellationToken cancellationToken)
{
IEnumerable<object?> handlers = ServiceProvider.GetServices(typeof(IEventHandler<>).MakeGenericType(@event.GetType()));
if (handlers.Any())
{
Type[] parameterTypes = [@event.GetType(), typeof(CancellationToken)];
object[] parameters = [@event, cancellationToken];
foreach (object? handler in handlers)
{
if (handler is not null)
{
MethodInfo? handle = handler.GetType().GetMethod(nameof(IEventHandler<>.HandleAsync), parameterTypes);
if (handle is not null)
{
await (Task)handle.Invoke(handler, parameters)!;
}
}
}
}
}
}
1 change: 0 additions & 1 deletion lib/Logitar.EventSourcing.Infrastructure/IEventBus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,5 @@ public interface IEventBus
/// <param name="event">The event to publish.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The asynchronous operation.</returns>

Task PublishAsync(IEvent @event, CancellationToken cancellationToken = default);
}