tags:

views:

25

answers:

2

Hi there,

How can I achieve this scenario?

I have a WCF service hosted in a windows form and whenever a client of the service calls a method on the service i want the service to be able to write a message to a textbox on the windows form.

I was thinking that i would make my WCF service a Singleton, pass my form using an Interface that the form implements, into the service and then store that instance. then when a client calls the service i can simply use the form instance to write to the textbox.

I cannot do this of course as i cannot pass a Form into a WCF service.

Any ideas or code samples?

+1  A: 

Take a look at this SO answer - as far as I understand it, it is basically the same question.

You can inject dependencies into WCF services: you just need to implement a custom ServiceHostFactory that wires everything up for you.

Mark Seemann
+1  A: 

The service instance and your Windows form are running in two separate threads, and you cannot just update a UI element on your main UI thread from the service instance.

You need to use a synchronization context and a delegate in order to properly and safely update your UI from the service thread.

See this CodeProject article - about in the middle, the author talks about the "UI thread woes". That's basically what you need to do:

SendOrPostCallback callback = 
    delegate (object state)
    {   
        yourListBox.Add(state.ToString());
    };

_uiSyncContext.Post(callback, guestName);

See Juval Lowy's MSDN article "WCF Synchronization Contexts" for a comprehensive introduction to the topic.

Hosting a WCF service inside a Winforms app seems like a rather bad idea to me - first of all because of all those threading issues, and secondly, it'll only ever work if the winforms app is up. Couldn't you put your WCF service into a console app or a Windows NT Service, and then just create a Winforms based monitoring app, that might check e.g. a database table for incoming request messages or something?

Marc

marc_s
Hosting a WCF service inside a rich client is a perfectly valid scenario. For instance, you can use it to implement callback channels, set up peer-to-peer networks, etc. WCF is much more than just a server-based technology.
Mark Seemann