Just… doing some practices.
Structure:
A Client WPF App and a Server WPF App, both of them Self Host a WCF service.
Client WPF contains a View, which contains the ListBox
What I want to do:
-
Server WPF will create channels to the Client’s WCF and constantly Send Message.
-
Client’s WCF will receive the message and boardcast to any classes that subscribe it. (Or maybe I will say the classes that observe it).
-
In this case, the Client’s View should receive message and put into the listbox.
Problems:
So the problem is how do I let the View observe the WCF? Or get notify by the WCF?
The Client’s WCF is created by using ServiceHost myHost = new ServiceHost(typeof(MyClient));
How can I let the WCF have reference to my Client’s View and do the notification?
Throught:
-
Somehow hardcoding the Client’s WCF to have the View reference internally (this…doesn’t make sense)
-
Observer Pattern? Make a static Subject class tht’s implement Client’s WCF Interface.
In the Client’s will routers all the methods calls to Subject class. The View will also implement Client’s WCF Interface and attaches to Subject class. Finally Subject class will routers calls to all the Views….
Something like this:
public class ClientServiceObserver : IClient
{
static List<IClient> _observers = new List<IClient>();
public static void Attach(IClient client)
{
_observers.Add(client);
}
public static void Detach(IClient client)
{
_observers.Remove(client);
}
public void SendCallbackMessage(string message)
{
foreach (IClient client in _observers)
{
client.SendCallbackMessage(message);
}
}
}
3.Everything similar to option 2, but instead of router all calls everywhere, might as well let WCF just notify Subject class there is update, then View will just get notify and create channel to Server to get it own data…..
All above options doens’t really sounds good… and option 2 I don’t even know if that’s Observer Patterns anymore….
I wonder what will be the best practice to do it?
Please look EventAggregator pattern to achieve what you are trying. EvenAggregator implementation are available in
See example for using EventAggregator here
You do not need to use the complete framework mentioned here, you can pull out the EventAggregator class and use it.