// ---------------------------------------------------------------------------- // To compile: // csc -debug+ -r:System.ServiceModel.dll SharedSessionSample.cs // // This sample is provided "AS IS" with no warranties, and confers no rights. // // Sample output: // C:\>SharedSessionSample // A: 1 // B: 10 // A: 2 // B: 20 using System; using System.ServiceModel; class App { public static void Main() { Binding tcpBinding = new NetProfileTcpBinding(); Uri tcpUri = new Uri("net.tcp://localhost/SharedSessionSample"); using (ServiceHost host = new ServiceHost()) { host.AddEndpoint(typeof(ICounter), tcpBinding, tcpUri); host.Open(); // Create objects A and B by creating a new channel to the service using (ICounterChannel a1 = ChannelFactory.CreateChannel(tcpUri, tcpBinding), b1 = ChannelFactory.CreateChannel(tcpUri, tcpBinding)) { // You can call methods first, and ResolveInstance later. a1.SetName("A"); EndpointAddress targetInstanceA = a1.ResolveInstance(); // Or you can call ResolveInstance first, and methods later. EndpointAddress targetInstanceB = b1.ResolveInstance(); b1.SetName("B"); // EndpointAddress is serializable. // Imagine we passed them as parameters or returned them to someone... // Connect to existing object by creating a channel to the object's EndpointAddress using (ICounterChannel a2 = ChannelFactory.CreateChannel(targetInstanceA, tcpBinding), b2 = ChannelFactory.CreateChannel(targetInstanceB, tcpBinding)) { a1.Increment(1); b1.Increment(10); a2.Increment(1); b2.Increment(10); a2.Close(); b2.Close(); } a1.Close(); b1.Close(); } host.Close(); } } } // ---------------------------------------------------------------------------- interface ICounterChannel : ICounter, IProxyChannel { } [ServiceContract] interface ICounter { [OperationContract] void SetName(string name); [OperationContract] int Increment(int n); } [ServiceBehavior(InstanceMode=InstanceMode.SharedSession)] class SharedSessionCounter : ICounter { string name = "NameNotSet"; int total = 0; public void SetName(string name) { this.name = name; } public int Increment(int n) { this.total += n; Console.WriteLine("{0}: {1}", this.name, this.total); return this.total; } }