开发者

WCF communicating with hosting app?

开发者 https://www.devze.com 2022-12-08 13:00 出处:网络
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 metho

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()
    {
开发者_JAVA技巧    }

    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!


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();


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消