我认为您的控制器不应该引发事件,在您完成特定域的验证后,这应该是您的域逻辑的东西。在您完成验证以确保它会起作用之前,您如何确定某些事情确实发生了?
然而,实现一个简单的基于事件的解决方案并不难。我会选择类似的东西:
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);
}
}
}
准备就绪后,您可以注册每个事件要执行的操作。我还没有编译它,但应该有类似的东西。