根据您链接到的示例,作者这样做:
Customer preferred = null;
DomainEvents.Register<CustomerBecamePreferred>(
p => preferred = p.Customer
);
c.DoSomething();
你应该能够做到这一点:
var model = new ViewModel();
// Register a handler that sets your bool to true if / when the event is raised
DomainEvents.Register<YourDomainEvent>(e => model.somethingComplicatedCausedSomethingElse = true);
// EDIT: If using the singleUseActions modification, pass the second parameter
// DomainEvents.Register<YourDomainEvent>(e => model.somethingComplicatedCausedSomethingElse = true, true);
// Call the service. If it raises the event, the handler you just registered will set your bool
service.doSomethingComplicated();
return View(model);
编辑(DomainEvents 修改)
这是未经测试的,并在 StackOverflow 编辑框中编写,但这是我要开始的地方。我正在使用一个可选参数,以便不需要修改现有调用,并使用一个单独的列表“singleUseActions”来尽可能保持现有的胆量不变。希望能帮助到你。
public static class DomainEvents
{
[ThreadStatic] //so that each thread has its own callbacks
private static List<Delegate> actions;
[ThreadStatic] //so that each thread has its own callbacks
private static List<Delegate> singleUseActions;
public static IContainer Container { get; set; } //as before
//Registers a callback for the given domain event
public static void Register<T>(Action<T> callback, bool isSingleUse = false) where T : IDomainEvent
{
List<Delegate> targetList;
if (isSingleUse)
{
if (singleUseActions == null) singleUseActions = new List<Delegate>();
targetList = singleUseActions;
}
else
{
if (actions == null) actions = new List<Delegate>();
targetList = actions;
}
targetList.Add(callback);
}
//Clears callbacks passed to Register on the current thread
public static void ClearCallbacks ()
{
actions = null;
singleUseActions = null;
}
//Raises the given domain event
public static void Raise<T>(T args) where T : IDomainEvent
{
if (Container != null)
foreach(var handler in Container.ResolveAll<Handles<T>>())
handler.Handle(args);
if (actions != null)
foreach (var action in actions)
if (action is Action<T>)
((Action<T>)action)(args);
if (singleUseActions != null)
// Don't foreach because we are going to modify the collection
for (int index = singleUseActions.Count - 1; index > -1; index--)
{
var singleUseAction = singleUseActions[index];
if (singleUseAction is Action<T>)
{
((Action<T>)singleUseAction)(args);
singleUseActions.RemoveAt(index);
}
}
}
}