XAML Playground
about XAML and other Amenities

Singleton ApplicationServices explained

2011-02-17T09:44:39+01:00 by Andrea Boschin

My has opened to some unexpected questions about what may seems a strangeness in my code. I was surprised about this questions, just because I believed it was a known pattern, so I decided to give an explanation to ones that does not know the reason I wrote some lines of code in the constructor

   1: public class SampleService : IApplicationService
   2: {
   3:     public static SampleService Current { get; private set; }
   4:  
   5:     /// <summary>
   6:     /// Initializes a new instance of the <see cref="ServiceHost"/> class.
   7:     /// </summary>
   8:     public SampleService()
   9:     {
  10:         if (SampleService.Current != null)
  11:             throw new InvalidOperationException("Service already exists");
  12:  
  13:         SampleService.Current = this;
  14:     }
  15:  
  16:     // omissis...
  17: }

The problem here is that sometimes it is not useful (and sometimes it is definitely bad) to have more than an instance of an ApplicationService running behind the scenes. Given that none can limit the number of instances in the ApplicationLifetimeObjects collection I use a pattern to avoid this problem.

First of all I expose a static property "Current". This property is useful to interact with the running service from any part of the code. Since after the beta there is not an indexer to access the running service this is the most common pattern used for this purpose.

Then in the constructor I check the property "Current" to be null. If I found a value it means someone is trying to put two instances of the service in the markup, so I raise an exception stating that only one instance is allowed. In the case "Current" is empty I save myself to this property using "this".

So nothing is wrong in my previous example. Only few lines of code to implement a Singleton pattern for IApplicationService, with a tecnique that is widely used also inside the framework classes.

Categories:   TIPS
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed