Hosting a singleton instance service
Singleton is a very popular design pattern used in application development. And for WCF services, sometimes it is useful to build a singleton-style service that will only use one instance object to serve all the operation calls from the client. This recipe will show you how to make a WCF service in singleton style.
How to do it...
In order to make a WCF service create a single instance of the Service type, we can apply InstanceContextMode
through ServiceBehaviorAttribute
on the service implementation type of our service. The following code snippet shows the sample service class, which has ServiceBehaviorAttribute
applied and the InstanceContextMode
property set to Single
.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class TimeService : ITimeService { public TimeService() { Console.WriteLine("A new instance of TimeService is constructedat {0}", DateTime.Now); } public DateTime GetCurrentTime() { return...