Search code examples
c#winformswcfself-hosting

Accessing a Self-Hosted WCF Service From the Host WinForms Program


I've created a Windows Forms app to run a WCF service that will be consumed essentially entirely by a single piece of software running on the same machine, and I would also like for the hosting app to serve as a "dashboard" that will display relevant status updates about the requests coming in for the sake of transparency. However although the Windows Forms app is being used to start and stop the service, I haven't been able to have it interact with it in any other meaningful way.

Some notes/what I've tried:

  • The service will only be accessed by one program (other than the hosting program, maybe)
  • The service is set to use InstanceContextMode.Single, but the SingletonInstance property of the ServiceHost object is always null.
  • Adding a service reference to it's own hosted service rendered the host program unresponsive (maybe not unexpectedly).

I apologize for the vagueness, but I basically took a stab at accessing the service object, and then the service itself. Am I missing something or is there an entirely better way to do this?

Thanks,

GBB

Edit: For clarity / the solution I wound up with - setting the host window reference as a static member of the host window's class that was accessible by the service.

public partial class frmMainWindow : Form
{
    public static frmMainWindow CurrentInstance;
    ServiceHost serviceHost;        

    public frmMainWindow ()
    {
        InitializeComponent();
        CurrentInstance = this;            
    }

    void StartService()
    {
        // service host stuff here for starting TestServer service
    }

    void StopService()
    {
        // stop the service
    }

    // update the status textbox in the host form
    public void SetStatus(string status)
    {
        textStatus.Text = status;
    }



[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class TestServer : ITestServer
{
    frmMainWindow HostWindow = null;

    public TestServer ()
    {
        HostWindow = frmMainWindow .CurrentInstance;
        HostWindow.SetStatus("Service started");
    }

Solution

  • Solution outlined in the edited original post - set a reference to the host window as a static member of the host window's class.