Can I call a method in a Self-Hosted WCF Service locally?

Unless you provide the service instance reference to the ServiceHost as a constructor parameter,

This line from Sixto's solution solved things for me. Credit and thanks to this post as well.

I'm using a duplex binding at the moment.


The key concept is that you can pass in a Type or an instance to the ServiceHost constructor.

So what I had before was:

 ServiceHost host = new ServiceHost(typeof(MyService), myUri);

What I needed was:

 MyService service = new MyService(foo);  // Can now pass a parameter
 ServiceHost host = new ServiceHost(service, myUri);

Also, I needed to mark MyService with

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 

...and now I can call the host's methods from inside the service.

However, keep in mind that the instance you created will not have an OperationContext if you call its methods directly: https://stackoverflow.com/a/15270541/385273

Good luck!


Unless you provide the service instance reference to the ServiceHost as a constructor parameter, there isn't a way to have the ServiceHost provide you an service instance reference. If you do provide that instance reference then you are creating a singleton service which is generally not a good idea.

To keep the service as it is configured, you will have to call it through a client. This is actually easier than you might think. Since your host code has access to the service contract, you can use it with the ChannelFactory class to get a proxy for the service. Besides the service contract, all you have to provide is the endpoint name and ChannelFactory will do the rest. Below is an example of how to do this:

private IMyServiceContract GetLocalClient(string serviceEndpointName)
{
    var factory = new ChannelFactory<IMyServiceContract>(serviceEndpointName);
    return factory.CreateChannel();
}

UPDATE: Along with this approach, you should consider having you service expose a NetNamedPipeBinding endpoint to improve performance. This binding pretty much does everything in memory and is the fastest binding for same machine service invocation.


For a WCF service instantiating more than once (non-singleton), you can maintain a list containing each instance's corresponding callback function as given here: mdsn. You can call the method CallClients() (from this MSDN example) from the hosting code directly as it is a static member of the service class. This is the only other way I found..


Old question, but here is another way to call a Singleton WCF Service hosted on a Windows Service

Following @Ben's requirements, the Service would need to be forced to be a Singleton:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 

Then:

var host = new ServiceHost(typeof(MyService), myUri);
var instance = (MyService)host.SingletonInstance;

That's it. Basically, the host already has a property that needs to be 'casted' to be able to access all the features from the Service.