out_sid3r
out_sid3r

Reputation: 1028

Windows Form and WCF service

I looked around and didn't find exactly what I'm looking for.

I have a windows form and a wcf service in the same project and I host the wcf service withing the form by doing the following:

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
ServiceHost host = new ServiceHost(typeof(Service1));
host.Open();

Application.Run(new Form1());
host.Close();

And the application which uses the service has no issues calling it.

My issue is now calling the wcf service's methods within the Windows Form. I could simply do

Service1 service = new Service1();
service.doWork();

But by doing this I'm not using the same instance as the clients of the Service (even if I use InstanceMode.Single) and I want to.

I know I could simply implement the windows form as a GUI Client of the web service (adding a service reference).

But I simply want to have the wcf service hosted in the windows form and access the same service instance as the wcf clients. How can I do that?

Upvotes: 0

Views: 2099

Answers (1)

Mike Goodwin
Mike Goodwin

Reputation: 8880

It only makes sense to "get the same instance of the clients" if you are using InstanceMode.Single, so that would be mandatory. If you are doing this, you can use the ServiceHost.SingletonInstance property. This gives you the instance (of type Object so you will have to cast it).

I think to make this work, you have to instantiate your ServiceHost with an instance of Service1 rather than with the type.

See this for details:

http://msdn.microsoft.com/en-us/library/ms585487.aspx

In which case, you could just keep hold of a reference to the instance that you use to create the ServiceHost, rather than the ServiceHost itself, saving you the extra call to ServiceHost.SingletonInstance...

Upvotes: 3

Related Questions