15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

service implementation ❘ 1297<br />

<br />

<br />

<br />

<br />

<br />

<br />

code snippet StateServiceSample/app.config<br />

If you start the service host with the defined configuration, an exception of type InvalidOperationException<br />

is thrown. The error message with the exception gives this error message: “Contract requires Session, but<br />

Binding ‘BasicHttpBinding’ doesn’t support it or isn’t configured properly to support it.”<br />

Not all bindings support all services. Because the service contract requires a session with the attribute<br />

[ServiceContract(SessionMode=SessionMode.Required)], the host fails because the configured<br />

binding does not support sessions.<br />

As soon as you change the configuration to a binding that supports sessions (for example, the<br />

wsHttpBinding), the server starts successfully:<br />

<br />

<br />

code snippet StateServiceSample/app.config<br />

Creating a Client Programmatically<br />

Now a client application can be created. In the previous example, the client application was created by<br />

adding a service reference. Instead of adding a service reference, you can directly access the assembly<br />

containing the contract interface <strong>and</strong> use the ChannelFactory class to instantiate the channel<br />

to connect to the service.<br />

The constructor of the class ChannelFactory accepts the binding configuration <strong>and</strong> endpoint<br />

address. The binding must be compatible with the binding defined with the service host, <strong>and</strong> the address<br />

defined with the EndpointAddress class references the URI of the running service.<br />

The CreateChannel() method creates a channel to connect to the service. Then, you can invoke methods<br />

of the service, <strong>and</strong> you can see that the service instance holds state until the Close() method that has the<br />

IsTerminating operation behavior assigned is invoked:<br />

using System;<br />

using System.ServiceModel;<br />

namespace Wrox.ProCSharp.WCF<br />

{<br />

class Program<br />

{<br />

static void Main()<br />

{<br />

var binding = new WSHttpBinding();<br />

var address = new EndpointAddress("http://localhost:8731/" +<br />

"Design_Time_Addresses/StateServiceSample/Service1/");<br />

var factory = new ChannelFactory(binding, address);<br />

IStateService channel = factory.CreateChannel();<br />

channel.Init(1);<br />

Console.WriteLine(channel.GetState());<br />

channel.SetState(2);<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!