WCF, Accessing a windows forms controls from a service

后端 未结 5 816
南旧
南旧 2021-01-05 22:17

I have a WCF service that is hosted inside a Windows Form.

How can I access the controls of the form from the methods in my service?

for example I have

5条回答
  •  暖寄归人
    2021-01-05 23:09

    The best way to handle such a scenario is to inject the Form into the service as a dependency. I would define some sort of interface that decouples the Form code from the WCF code:

    public interface IFormService
    {
        string Text { get; set; }
    }
    

    You can have your Form implement the IFormService interface by setting the real property you would like to update.

    Your service would need an instance of IFormService to do its work:

    public class Service : IService
    {
        private readonly IFormService form;
    
        public Service(IFormService form)
        {
            this.form = form
        }
    
        public string PrintMessage(string message)
        {
            this.form.Text = message;
        }
    }
    

    Since the Service class now has no default constructor, you will also need to implement a custom ServiceHostFactory that can create instances of the Service class and inject the concrete implementation of IFormService.

提交回复
热议问题