How can a self-hosted (WinForm ) WCF service interact with the main form?

前端 未结 3 464
借酒劲吻你
借酒劲吻你 2020-12-10 09:33

Simplified version of what I\'m trying to achieve:

  • I have a WinForms app that runs hidden (Visible = false) in the background.
  • It\'s got only one Form
3条回答
  •  天涯浪人
    2020-12-10 10:04

    Can you use a singleton for your service? If so you could implement it like this:

    [ServiceContract]
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class MyClass : IMyClass
    {
        Form1 _f;
        public MyClass(Form1 f)
        {
            _f = f;
        }
    
        [OperationContract]
        public void Alert(string mess)
        {
            _f.Text = mess;
        }
    }
    

    Then when you setup your service host, you instantiate it and pass it the form:

    MyClass c = new MyClass(this);
    string baseAddress = "http://localhost:12345/Serv";
    var host = new ServiceHost(c, new Uri(baseAddress));
    

提交回复
热议问题