如何解决在asp.net mvc控制器中处理域事件
| 我正在研究使用域事件来泡沫化来自域模型内部的操作的信息,以便在控制器级别发出某些事件的信号。不幸的是,我还找不到如何在asp.net mvc控制器上正确连线的示例。 简而言之,这就是我要在动作中寻找的内容:service.doSomethingComplicated();
var model = new viewmodel();
model.somethingComplicatedCausedSomethingElse = <true-if-my-domain-event-was-raised>;
return View(model);
谁能给我一些指导?
更新资料
明确起见,我了解如何在控制器中引发和处理域事件。我只是在寻找一种注册事件的实现方法,该方法在我描述的上下文中可以安全使用。
解决方法
根据您链接到的示例,作者在其中进行以下操作:
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);
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。