我正在尝试将事件用作 3 层应用程序中层之间的一种通信形式,因为建议使用事件来避免层之间的耦合。但是,当结果中需要同步响应时,我无法弄清楚如何使用事件,例如 MVC Web 应用程序。考虑下面的例子
//1. Repository for Employee (Database Tier)
interface IEmployeeRepository
{
//event to signal add complete in repository
public event EventHandler event_EmployeeAdded_To_Repository;
void AddEmployee(Employee emp);
}
public class EmployeeRepository: IEmployeeRepository
{
//implementation of event
public event EventHandler event_EmployeeAdded_To_Repository;
public void AddEmployee(Employee emp)
{
//Save to database
//Fire event to signal add complete in repository
event_EmployeeAdded_To_Repository(null,e);
}
}
//2. Business Tier for Employee
interface IEmployee
{
//event to signal add complete in business tier
public event EventHandler event_EmployeeAdded_To_Entity;
public void AddEmployee();
}
public class Employee : IEmployee
{
public event EventHandler event_EmployeeAdded_To_Entity;
IEmployeeRepository _empRepository;
//constructor injection
public Employee(IEmployeeRepository empRepository)
{
this._empRepository = empRepository;
//Add event handler for the repository event
this._empRepository.event_EmployeeAdded_To_Repository += OnEmployeeAddedToRepository;
}
public void AddEmployee()
{
//Call repository method for adding to database
_empRepository.AddEmployee(this);
}
//Event handler for the repository event
public void OnEmployeeAddedToRepository(Object sender, EventArgs e)
{
//Fire event to signal add complete in business tier
event_EmployeeAdded_To_Entity(null, e);
}
}
//3. Presentation Tier
public class EmployeeController : Controller
{
IEmployee _emp;
//constructor injection
public EmployeeController(IEmployee emp)
{
this._emp = emp;
//Add event handler for business tier event
this._emp.event_EmployeeAdded_To_Entity += OnEmployeeAddedToEntity;
}
//This is an Ajax method call
public ActionResult Add()
{
//Call add method of business tier
_emp.AddEmployee();
//What do I do here ?
}
//Event handler for the business tier event
public void OnEmployeeAddedToEntity(Object sender, EventArgs e)
{
//What do I do here ?
}
}
在上面的示例中,我在存储库(数据库层)中定义了事件“event_EmployeeAdded_To_Repository”以通知存储库中的添加完成。在业务层中,我定义了处理此事件的事件处理程序“OnEmployeeAddedToRepository”。“OnEmployeeAddedToRepository”事件处理程序依次触发事件“event_EmployeeAdded_To_Entity”。最后,在表示层中,我定义了事件处理程序“OnEmployeeAddedToEntity”来处理业务层事件。
但是在控制器中,我有一个动作“Add”需要同步返回响应(在“AddEmployee”完成之后)以通知用户(或者可能调用另一个 ajax 动作)。触发事件只会将控制流从操作更改为事件处理程序。
那么在这种情况下你将如何使用事件呢?