Robert Smith
Robert Smith

Reputation: 779

Starting a WCF from its own class constructor

I have a self hosted named pipes (not using http) wcf hosted in a class library. I am able to start the WCF by using the following method in the class library:

ServiceHost serviceHost;
public void startService()
{
    // Create the service host
    ...
    // Open Service Host
    serviceHost.Open();
}

And then from a winforms test program running the following from a button click:

MyClassLib.MySvc testSvc;
private void button2_Click(object sender, EventArgs e)
{
    testSvc = new MyClassLib.MySvc();
    testSvc.startService();
}

This does correctly start the WCF running in the class library.

But this requires the winforms that is referencing the class library to call startService method.

What I would like is just to be able to start the service as soon as a reference to the class library that will be running the WCF is done.

I have attempted to add the following in the class library service's constructor:

public MySvc()
{
    startService();
}

And then instantiate from the winforms:

MyClassLib.MySvc testSvc;
private void button2_Click(object sender, EventArgs e)
{
    testSvc = new MyClassLib.MySvc();
    //testSvc.startService();  //No need to call this
}

If I debug the code, I can see that in fact it does break at this point:

public MySvc()
{
    startService();  // It does run this but service does not start
}

But this does not run the service. Any help would be appreciated.

Note #1: I believe its some type of timing issue where it does not let you start the service during the constructor method but not sure of that.

Upvotes: 0

Views: 111

Answers (1)

Robert Smith
Robert Smith

Reputation: 779

Problem resolved and yes my assumption that it was a timing issue (See Note# 1 above) was correct!

To replicate, change this:

public MySvc()
{
    startService();  // It does run this but service does not start
}

To this and problem solved:

public void delayStartService()
{
    Task.Delay(1000).ContinueWith(t => startService());
}

public MySvc()
{
    delayStartService();
}

Upvotes: 1

Related Questions