tags:

views:

89

answers:

2

I am hosting a WCF service inside of a WPF app. I would like the WCF to be able to communicate with its host. Specifically, I'd like to receive event notifications from the WCF when certain WCF methods are called by clients.

I've tried modifying my WCF to be a singleton like so:

[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 the main form of the hosting WPF app using the Instance property to interact with the WCF, but this doesn't appear to work. It's almost as if the call from the client to the WCF is instantiating a new WCF. Help!

+1  A: 

You may be spinning up your ServiceHost in the wrong way, then. When you use InstanceContextMode.Single, you should create your ServiceHost with that particular instance:

var host = new ServiceHost(_instance);
//...
host.Open();
Mark Seemann
That's what I figured out. I went ahead and posted a more lengthy answer, but yours is accurate. Thanks!
David Lively
A: 

Found an answer that works.

My 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've also modified the service class by adding the attribute:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class MasterNode : ServiceBase, IMasterNode

The serviceHost object then uses the instance I explicitly created. Note that the parameter passed to the ServiceHost constructor is an instance of MasterNode, not a type reference.

Hope this helps someone else!

David Lively