Previous | Home | Next |
The singleton service is the ultimate sharable service.
When you configure a service as a singleton, all clients are independently connected to the same single well-known instance context and implicitly to the same instance inside, regardless of which endpoint of the service they connect to the singleton is created exactly once, when the host is created, and lives forever: it is disposed of only when the host shuts down.
///////////////////////// Service code ///////////////////// [ServiceContract(SessionMode = SessionMode.Required)] interface IMyContract { [OperationContract] void operation1( ); } [ServiceContract(SessionMode = SessionMode.NotAllowed)] interface IMyOtherContract { [OperationContract] void operation2( ); } [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] class MySingleton : IMyContract,IMyOtherContract,IDisposable { int flag = 0; public MySingleton( ) { Trace.WriteLine("MySingleton.MySingleton( )"); } public void operation1( ) { flag++; Trace.WriteLine("Counter = " + flag); } public voidoperation2( ) { flag++; Trace.WriteLine("Counter = " + flag); } public void Dispose( ) { Trace.WriteLine("Singleton.Dispose( )"); } } ///////////////////////// Client code ///////////////////// MyContractClient proxy1 = new MyContractClient( ); proxy1.operation1( ); proxy1.Close( ); MyOtherContractClient proxy2 = new MyOtherContractClient( ); proxy2.MyOtherMethod( ); proxy2.Close( ); //Output MySingleton.MySingleton( ) Counter = 1 Counter = 2
Initializing a Singleton
//Service code [ServiceContract] interface IMyContract { [OperationContract] void operation( ); } [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] class MySingleton : IMyContract { int flag = 0; public int Counter { get { return flag; } set { flag = value; } } public void operation( ) { flag++; Trace.WriteLine("Counter = " + Counter); } } //Host code MySingleton singleton = new MySingleton( ); singleton.Counter = 100; ServiceHost host = new ServiceHost(singleton); host.Open( ); //Do some blocking calls then host.Close( ); //Client code MyContractClient proxy = new MyContractClient( ); proxy.operation( ); proxy.Close( ); //Outoput: Counter = 101
Previous | Home | Next |