I have classes that need to communicate with each other. The problem is that if you create one of them, then the other (child parent relationships), then everything becomes complicated. You either need to pass the parent instance to the child (then which one you create first if you use dependency injection), or you can use delegates / events. But I want to emphasize the fact that the parent should be able to handle the event that the child raises. Not too sure how to do this. I also do not want to use multiple subscribers.
The relationship between parent and child just feels wrong for two-way communication. Unfortunately, this is not the case when one of the objects is always triggered, and the other responds. Anyone can start, and the other must answer.
Is there any other template that I am missing?
UPDATE: Sorry, this is pretty hard to explain. I forgot to add that when one class sends a message to another class, it does not expect a response immediately. The answer comes asynchronously, so you need an instance of the parent to call the correct method or delegate / event. Sorry, the example below is pseudo code. I hope this is enough to understand this idea. Should I look at the reseller template.
public class Foo
{
public void SendMessageAToBar()
{
MessageA msg = new MessageA();
Bar.ReceiveMessageAFromFoo(msg);
}
public void ReceiveMessageARespFromBar(MessageAResp msgResp)
{
}
public void ReceiveMessageBFromBar(MessageB msg)
{
MessageBResp msgBResp = new MessageBResp();
Bar.ReceiveMessageBRespFromFoo()
}
}
public class Bar
{
public void ReceiveMessageAFromFoo(MessageA msg)
{
MessageAResp resp = new MessageAResp();
Foo.ReceiveMessageARespFromBar(resp);
}
public void SendMessageBToFoo()
{
MessageB msg = new MessageB();
Foo.ReceiveMessageBFromBar(msg);
}
public void ReceiveMessageBRespFromFoo(MessageBResp msgResp)
{
}
}
source
share