WCF communicating with the hosting application?
I am hosting a WCF service inside a WPF application. I would like WCF to be able to communicate with its host. Specifically, I would like to receive event notifications from WCF when certain WCF methods are called by clients.
I've tried modifying my WCF as a one-liner:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public sealed class MasterNode : ServiceBase, IMasterNode
{
private static readonly MasterNode _instance = new MasterNode();
public static MasterNode Instance { get { return _instance; } }
private MasterNode()
{
}
static MasterNode()
{
}
and having a basic form of hosting a WPF application using the Instance property to interact with WCF, but that doesn't seem to work. It is almost as if the call from the client to WCF was creating a new WCF. Help!
source to share
Found an answer that works.
The WPF main window constructor looks like this:
public partial class Main : Window
{
private ObservableCollection<GridNodeProxy> _gridNodes = new ObservableCollection<GridNodeProxy>();
private static Random _random = new Random();
public MasterNode MasterNode { get; set; }
private ServiceHost _serviceHost;
public Main()
{
this.MasterNode = new MasterNode();
MasterNode.OnMessage += MasterNodeMessage;
_serviceHost = new ServiceHost(MasterNode);
_serviceHost.Open();
InitializeComponent();
}
I also changed the service class by adding an attribute:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class MasterNode : ServiceBase, IMasterNode
The serviceHost object then uses the explicitly instantiated instance. Note that the parameter passed to the ServiceHost constructor is a MasterNode instance, not a type reference.
Hope this helps someone else!
source to share