I am writing two applications in C# that need to be able to communicate (in one direction only). The two apps will always run on the same machine, so using WCF with named pipes, and self-hosting the WCF service, seemed like the logical choice.
I understand that I can use InstanceContextMode to configure if a service instance is instantiated per session, per call, or if there should just be a single instance. In my case I want a single instance, because I will have just the two apps running, so there will be a single client and a single server.
But here’s where I’m stuck. When my client makes a call on the service, which I’m doing this way:
var myServiceFactory = new ChannelFactory<IMyService>(
new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyService"));
IMyService myService = myServiceFactory.CreateChannel();
myService.DoStuff();
I don’t want a new server object instance to be created on the server. Instead I’d like myService to point at the (one and only) IMyService instance that has already been constructed on the server. At the moment, a second IMyService instance gets constructed.
In other words, I want my server object to be constructed by the server (when the server starts up), not when a client first makes a call.
Can anyone explain how to do this? From what I understand, .NET Remoting makes this quite easy, and WCF has supposedly replaced Remoting, so there must be an easy way… right?
WCF’s
ServiceHosthas a constructor which takes a singleton instance of the service class rather than the service type, for exactly this purpose. You must set InstanceContextMode to Singleton if using this constructor in your service host.Note that in the client side code you quote,
IMyService myServiceis not what you call “the server object” … it is the client-side proxy through which WCF routes messages from the client to the actual service.