tags:

views:

963

answers:

2

I am doing a WPF application and it is also a WCF server, the problem I have is that I need the ServiceHost to be open and listen in a port for the clients and accept requests as soon as it starts, but the problem I have is that if I write the code to open the host host.open in the constructor after the function this.InitializeComponent(), it fails with an exception. If I open the host in a button and I press it after the app started, it works without any problems.

Why is that and how can I resolve this issue?

I am utilizing a tcp.net channel,I am hosting it in the application and the exception I receive is about the service already was registered.

The exception on the clients is:

inner exception message :"An existing connection was forcibly closed by the remote host"
error number: 10054
Socket error: System.Net.Sockets.SocketError.ConnectionReset

thanks

Wally

the constructor is:

public Window1()
{
   this.InitializeComponent();
   starthost();  
}

private void starthost()
{
   host = new ServiceHost(typeof (Window1), 
                           new Uri[]{ new Uri("net.tcp://localhost:8000") });

   host.AddServiceEndpoint(typeof(IGanador), new NetTcpBinding(), "Contador");
   host.open(); //it fails with this line here but not in a button 
}
+1  A: 

So do I get this correctly? Your "Window1" is a WPF window class, which implements the service contract IGanador? That seems a bit odd.... how about just creating a class of its own, e.g. "GanadorService", which implements IContador? Then this CLASS would be created / instantiated for each request - not your window.

public Window1()
{
   this.InitializeComponent();
   starthost();  
}

private void starthost()
{
   host = new ServiceHost(typeof (GanadorService), 
                           new Uri[]{ new Uri("net.tcp://localhost:8000") });

   host.AddServiceEndpoint(typeof(IGanador), new NetTcpBinding(), "Contador");
   host.open(); //it fails with this line here but not in a button 
}


public class GanadorService : IGanador
{
   .... (whatever methods you need) .....
}

That should help, I hope!

Marc

marc_s
I did it like that because I need to change the gui and I wasn't sure how to pass a handle of my window to the class implementing the interface for the Servicehost. Because I don't call the constructor but the ServiceModel does it directly. is there a way to do that? thanks...
A: 

Hi
I resolved the problem thanks a lot to the comments of marc_s
I created a singlenton servicehost
adding the following attribute to my window1

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

and passing this in the constructor:

host = new ServiceHost( this , new Uri[]{ new Uri("net.tcp://localhost:8000 });

it works great because I only have one client anyway

thanks
this is a link with a great article with the explanation of WCF instance managment:

http://msdn.microsoft.com/en-us/magazine/cc163590.aspx