Skip to content

Commit

Permalink
Refactor TinyEventBus
Browse files Browse the repository at this point in the history
  • Loading branch information
agile.zhou committed Sep 8, 2024
1 parent 1b6cd3b commit 12286f0
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ public static class ServiceCollectionExt
{
public static IServiceCollection AddTinyEventBus(this IServiceCollection sc)
{
sc.AddSingleton<ITinyEventBus, TinyEventBus>(sp => new TinyEventBus(sc));
sc.AddSingleton<ITinyEventBus, TinyEventBus>(sp =>
new TinyEventBus(sc));
return sc;
}
}
Expand Down
37 changes: 19 additions & 18 deletions src/AgileConfig.Server.Common/EventBus/TinyEventBus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,41 +37,42 @@ public void Register<T>() where T : class, IEventHandler

public void Fire<TEvent>(TEvent evt) where TEvent : IEvent
{
IServiceProvider sp = _serviceCollection.BuildServiceProvider();
var sp = _serviceCollection.BuildServiceProvider();
using var scope = sp.CreateScope();
var logger = sp.GetService<ILoggerFactory>().CreateLogger<TinyEventBus>();
var logger = scope.ServiceProvider.GetService<ILoggerFactory>().CreateLogger<TinyEventBus>();

logger.LogInformation($"Event fired: {typeof(TEvent).Name}");

var eventType = typeof(TEvent);
if (_eventHandlerMap.TryGetValue(eventType, out List<Type> handlers))
{
if (handlers.Count == 0)
{
logger.LogInformation($"Event fired: {typeof(TEvent).Name}, but no handlers.");
return;
}

foreach (var handlerType in handlers)
{
_ = Task.Run(async () =>
{
using (var scope = sp.CreateScope())
using var sc = sp.CreateScope();
var handler = sc.ServiceProvider.GetService(handlerType);
if (handler != null)
{
var handler = sp.GetService(handlerType);
if (handler != null)
var handlerInstance = handler as IEventHandler;
try
{
var handlerIntance = handler as IEventHandler;
try
{
await handlerIntance.Handle(evt);
}
catch (Exception ex)
{
logger.LogError(ex, "try run {handler} occur error.", handlerType);
}
await handlerInstance.Handle(evt);
}
catch (Exception ex)
{
sc.ServiceProvider.GetService<ILoggerFactory>().CreateLogger<TinyEventBus>()
.LogError(ex, "try run {handler} occur error.", handlerType);
}
}
});
}
if (handlers.Count == 0)
{
logger.LogInformation($"Event fired: {typeof(TEvent).Name}, but no handlers.");
}
}
}
}
Expand Down

0 comments on commit 12286f0

Please sign in to comment.