Subversion Repositories Projects

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2287 - 1

2
namespace GMap.NET
3
{
4
   using System;
5
   using System.Diagnostics;
6
   using System.Reflection;
7
 
8
   /// <summary>
9
   /// generic for singletons
10
   /// </summary>
11
   /// <typeparam name="T"></typeparam>
12
   public class Singleton<T> where T : new()
13
   {
14
      // ctor
15
      protected Singleton()
16
      {
17
         if(Instance != null)
18
         {
19
            throw (new Exception("You have tried to create a new singleton class where you should have instanced it. Replace your \"new class()\" with \"class.Instance\""));
20
         }
21
      }
22
 
23
      public static T Instance
24
      {
25
         get
26
         {
27
            if(SingletonCreator.exception != null)
28
            {
29
               throw SingletonCreator.exception;
30
            }
31
            return SingletonCreator.instance;
32
         }
33
      }
34
 
35
      class SingletonCreator
36
      {
37
         static SingletonCreator()
38
         {
39
            try
40
            {
41
               instance = new T();
42
            }
43
            catch(Exception ex)
44
            {
45
               if(ex.InnerException != null)
46
               {
47
                  exception = ex.InnerException;
48
               }
49
               else
50
               {
51
                  exception = ex;
52
               }
53
               Trace.WriteLine("Singleton: " + exception);
54
            }
55
         }
56
         internal static readonly T instance;
57
         internal static readonly Exception exception;
58
      }
59
   }
60
}