I am looking for a way to handle an event raised by class A in class B without coupling the classes.
The situation is that class A is a state machine. I need to send an email when a state of class A becomes Active. I would like to create a class that would listen up for that event and handle it.
I encapsulate the state logic in class A and I instantiate it from a web page (asp.net webform).
I could instantiate the email class inside the webform as well, but I do not wish to do so, in that case, the developer that codes the webform will have to hook up the logic and events. I would like to push all that logic back to the business layer. But I can't seem to have a way to do it.
in BLL
class StateHandler()
{
public event EventHandler StateChanged;
SetState(int newState)
{
// to keep things simple for sample let's assume 2 states
if (newState ==1 ) this.State = "Active";
else this.State = "Inactive";
if (this.StateChanged != null)
this.StateChanged(this, new EventArgs());
}
}
class EmailProvider()
{
SendEmail()
{
// logic to send email
}
}
Asp.net page
....
void OnSubmit_click()
{
StateHandler sh = new StateHandler();
//adds an event handler to the StateChanged event
sh.StateChanged += new EventHandler(sh_StateChanged);
//setting this will fire the StateChanged event
sh.SetState(1);
}
EventBus might be a useful pattern for your case. It is simply a message broker that passes events to registered subscribers. I don't know if there is any C# library for that. But is should be easily implemented. Have a look at guava's EventBus. It's Java but you shoud get the idea.
In a container managed situation like EJB the container handles asynchronous message dispatch. In Java/Java EE again you'd have Message Driven Beans.