diff --git a/src/AgileConfig.Server.Common/EventBus/ServiceCollectionExt.cs b/src/AgileConfig.Server.Common/EventBus/ServiceCollectionExt.cs index d5742a8f..4c35b991 100644 --- a/src/AgileConfig.Server.Common/EventBus/ServiceCollectionExt.cs +++ b/src/AgileConfig.Server.Common/EventBus/ServiceCollectionExt.cs @@ -6,7 +6,8 @@ public static class ServiceCollectionExt { public static IServiceCollection AddTinyEventBus(this IServiceCollection sc) { - sc.AddSingleton(sp => new TinyEventBus(sc)); + sc.AddSingleton(sp => + new TinyEventBus(sc)); return sc; } } diff --git a/src/AgileConfig.Server.Common/EventBus/TinyEventBus.cs b/src/AgileConfig.Server.Common/EventBus/TinyEventBus.cs index b25a6206..067700cb 100644 --- a/src/AgileConfig.Server.Common/EventBus/TinyEventBus.cs +++ b/src/AgileConfig.Server.Common/EventBus/TinyEventBus.cs @@ -37,41 +37,42 @@ public void Register() where T : class, IEventHandler public void Fire(TEvent evt) where TEvent : IEvent { - IServiceProvider sp = _serviceCollection.BuildServiceProvider(); + var sp = _serviceCollection.BuildServiceProvider(); using var scope = sp.CreateScope(); - var logger = sp.GetService().CreateLogger(); + var logger = scope.ServiceProvider.GetService().CreateLogger(); logger.LogInformation($"Event fired: {typeof(TEvent).Name}"); var eventType = typeof(TEvent); if (_eventHandlerMap.TryGetValue(eventType, out List 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().CreateLogger() + .LogError(ex, "try run {handler} occur error.", handlerType); } } }); } - if (handlers.Count == 0) - { - logger.LogInformation($"Event fired: {typeof(TEvent).Name}, but no handlers."); - } } } }