【发布时间】:2015-08-13 15:19:53
【问题描述】:
我有一个系统,它基本上用于解决异常并输出 CSV on demand,其中详细说明了每个已解决的项目。每天都会有新的异常需要处理。我的控制器中有一个POST 方法:
[HttpPost]
private ActionResult Resolve(ExceptionViewModel modifiedExceptionViewModel, string currentFilter)
{
// resolve database records...
return RedirectToAction("Index", "Exceptions");
}
我有一个新要求,但是,用户希望系统识别最后一个未解决的解决方案,然后自动将 CSV 输出到文件共享,而不是必须手动执行此操作。
我首先创建了一个方法来检查这是否是最后一个异常,并将其称为 WasLastException(); 我知道我可以将其包装在一个 IF 语句中,并且在真正调用我称为 OutputMasterFileCsv(); 的方法时在这样做之前,我想我会第一次尝试代表/事件,这让我得到了类似的结果,但也提出了一些问题。
我的申请的一些背景
这是一个使用 Unity DI 的 Entity Framework Code First MVC Web 应用程序,我已将所有存储库调用包装在核心层的 ProcessDataService 类中,该类具有正在向 Unity 注册的接口 IProcessDataService。
这就是我尝试添加事件的方式:
控制器的构造函数
public ExceptionsController(IProcessDataService service)
{
_service = service; //publisher
//event for delegate
OutputService outputService = new OutputService(_service); //subscriber
_service.LastException += outputService.OnLastException;
}
输出服务
public void OnLastException(object source, EventArgs e)
{
// output the CSV
}
流程数据服务
public delegate void LastExceptionEventHandler(object source, EventArgs args);
public class ProcessDataService : IProcessDataService
{
private readonly IExceptionRepository _exceptionRepository;
public ProcessDataService(IExceptionRepository evpRepo)
{
_exceptionRepository = evpRepo;
}
public event LastExceptionEventHandler LastException;
public void OnLastException()
{
if (LastException != null)
LastException(this, EventArgs.Empty);
}
}
Controller 中的新 Resolve 方法
[HttpPost]
private ActionResult Resolve(ExceptionViewModel modifiedExceptionViewModel, string currentFilter)
{
// resolve database records...
if(_service.WasLastException())
{
//raise the event
_service.OnLastException();
}
return RedirectToAction("Index", "Exceptions");
}
这一切都很好,但是我觉得我在这里没有在正确的地方使用委托和事件,而不是调用上面的OnLastException() 并使用事件,我为什么不只是简单地调用@ 987654330@ 已经位于我的ProcessDataService 类中?
我相信这与松散耦合有关,但我不完全了解这实际上有什么好处,或者我完全不理解这一切......?
我想无论如何我都会在有机会并希望学到新东西的时候放弃它。如果有更多经验的人可以介入并提供一些指导,我将不胜感激,因为我现在有点迷茫。
【问题讨论】:
标签: c# asp.net-mvc events delegates