我不認爲你的控制器應該引發事件,這應該是你的域邏輯完成域特定驗證後的事情。在完成驗證之前,你如何確定事情真的發生了,以確保它能正常工作?
但是,實現基於事件的簡單解決方案並不難。我會去這樣的:
public abstract class BaseEvent {}
public class EventRouter {
private Dictionary<Type, List<Action<BaseEvent>>> _eventRoutes;
public EventRouter()
{
_eventRoutes= new Dictionary<Type, List<Action<BaseEvent >>>();
}
public void Register<TEvent>(Action<TEvent> route) where TEvent : BaseEvent
{
List<Action<TEvent>> routes;
var type = typeof(BaseEvent);
if (_eventRoutes.TryGetValue(type, out routes).IsFalse())
{
routes = new List<Action<TEvent>>();
_eventRoutes.Add(type, routes);
}
routes.Add((y) => route(y as BaseEvent));
}
public bool TryGetValue(Type commandType, out List<Action<TEvent>> handlers)
{
return _eventRoutes.TryGetValue(eventType, out handlers);
}
}
public class InMemoryEventDispatcher : IEventBus
{
private readonly IEventRouter _eventRouter;
public InMemoryEventBus(IEventRouter eventRouter)
{
_eventRouter = eventRouter;
}
public void PublishEvent<TEvent>(TEvent @event) where TEvent : BaseEvent
{
var eventType = @event.GetType();
List<Action<TEvent>> eventHandlers;
if (_eventRouter.TryGetValue(eventType, out eventHandlers).IsTrue())
{
foreach (var eventHandler in eventHandlers)
{
eventHandler(@event);
}
}
}
public void PublishEvents<TEvent>(IEnumerable<BaseEvent> events) where TEvent : BaseEvent
{
foreach (var @event in events)
{
PublishEvent(@event);
}
}
}
隨着那個準備好,你可以註冊你想要執行每個事件的動作。我沒有編譯它,但是應該這樣。
@downvoter,請評論有什麼不對? –