An applied example can be found in the project in the example/ directory.
Examples are based off of a Unity3D application of this library.
public interface IExampleEvent
{
}
public class UnityEventBusErrorHandler : IEventBusErrorHandler
{
public void Handle(Type eventType, Exception exception)
{
var msg = $"{exception.GetType().Name} error handling a {eventType} event: {exception.Message}";
Debug.LogError(msg);
Debug.LogException(exception);
}
}
public static IServiceCollection ConfigureCentralStructEventBus<TBase>(this IServiceCollection serviceCollection)
{
return serviceCollection
.AddSingleton<ICentralStructEventBus<TBase>, CentralStructEventBus<TBase>>()
.AddSingleton<IInlineBranchStructEventBus<TBase>, InlineStructEventBus<TBase>>()
.AddSingleton<IAsyncDeferredBranchEventRepository<TBase>, AsyncDeferredEventRepository<TBase>>()
.AddSingleton<IDeferredBranchEventRepository<TBase>, DeferredEventRepository<TBase>>();
}
public static IServiceCollection ConfigureServices(this IServiceCollection serviceCollection)
{
return serviceCollection
.ConfigureCentralStructEventBus<IExampleEvent>()
.AddSingleton<IEventBusErrorHandler, UnityEventBusErrorHandler>();
}Listeners inherit from either IBusEventHandler<TBase> or IAsyncBusEventHandler<TBase>
private IAsyncDeferredBranchEventRepository<IExampleEvent> EventBusAsyncRepo { get; set; }
private async Task RunEventThread(CancellationToken cancellationToken = default)
{
while (true)
{
await EventBusAsyncRepo.WaitForEventAsync(cancellationToken);
await EventBusAsyncRepo.RunUntilEmptyAsync(cancellationToken);
}
}Based off of Unity project
private IDeferredEventRepository<IExampleEvent> EventBusSyncRepo { get; set; }
public void FixedUpdate()
{
// Pull events and execute in batches lasting up to 5ms
EventBusSyncRepo?.RunBatch(5);
}