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?
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 eg a database table for incoming request messages or something?
Marc
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.