티어 간의 연결을 피하기 위해 이벤트가 권장되는 방법이므로 3 계층 응용 프로그램의 티어 사이의 통신 형식으로 이벤트를 사용하려고합니다. 그러나 MVC 웹 응용 프로그램의 경우처럼 결과에 동기식 응답이 필요한 경우 이벤트를 사용하는 방법을 파악할 수 없습니다. 위의 예에서, 예MVC 응용 프로그램에서 티어 간의 통신을 위해 이벤트를 사용하는 방법
//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 ?
}
}
이하 고려 I는 저장소에 첨가 완료를 알리기 위해 리포지토리 (데이터베이스 계층)에서 이벤트 「event_EmployeeAdded_To_Repository "을 정의했다. 비즈니스 계층에서이 이벤트를 처리하는 이벤트 처리기 "OnEmployeeAddedToRepository"를 정의했습니다. "OnEmployeeAddedToRepository"이벤트 처리기는 차례로 이벤트 "event_EmployeeAdded_To_Entity"를 시작합니다. 마지막으로 프레젠테이션 계층에서 비즈니스 계층 이벤트를 처리하기위한 이벤트 처리기 "OnEmployeeAddedToEntity"를 정의했습니다.
컨트롤러에는 사용자에게 알리기 위해 ("AddEmployee"완료 후) 응답을 동 기적으로 반환해야하는 "추가"작업이 있습니다 (또는 다른 아약스 액션을 호출 할 수도 있음). 이벤트를 발생 시키면 액션에서 이벤트 핸들러로 컨트롤의 흐름이 변경됩니다.
그렇다면이 시나리오에서 어떻게 이벤트를 사용 하시겠습니까?