Tag Archives: c#

A singleton base class to implement the singleton pattern in C#

The singleton design pattern is one of the most controversial pattern. Some people even call it anti-pattern, evil, or stupid. I won’t go into the debate now, but I just want to share something for those who need to use singletons.

Although it is one of the easiest pattern to understand, it is also very easy to code it poorly, leading to unexpected side effects such as poor performance or being not thread-safe.

Jon Skeet has written a very good article describing different implementations of the singleton pattern in C#. He gives a nice example on how you can write a singleton code that is thread-safe and lazy-instantiating. The code is less than 20 lines and you can use it as a template for your singletons.

Since in some projects I have created several singleton objects, it started to get repetitive. Therefore I decided to write a base class based on this pattern as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Globalization;
using System.Reflection;
 
public abstract class SingletonBase<T> where T : class
{
    /// <summary>
    /// A protected constructor which is accessible only to the sub classes.
    /// </summary>
    protected SingletonBase() { }
 
    /// <summary>
    /// Gets the singleton instance of this class.
    /// </summary>
    public static T Instance
    {
        get { return SingletonFactory.Instance; }
    }
 
    /// <summary>
    /// The singleton class factory to create the singleton instance.
    /// </summary>
    class SingletonFactory
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static SingletonFactory() { }
 
        // Prevent the compiler from generating a default constructor.
        SingletonFactory() { }
 
        internal static readonly T Instance = GetInstance();
 
        static T GetInstance()
        {
            var theType = typeof(T);
 
            T inst;
 
            try
            {
                inst = (T)theType
                    .InvokeMember(theType.Name,
                    BindingFlags.CreateInstance | BindingFlags.Instance
                    | BindingFlags.NonPublic,
                    null, null, null,
                    CultureInfo.InvariantCulture);
            }
            catch (MissingMethodException ex)
            {
                throw new TypeLoadException(string.Format(
                    CultureInfo.CurrentCulture,
                    "The type '{0}' must have a private constructor to " +
                    "be used in the Singleton pattern.", theType.FullName)
                    , ex);
            }
 
            return inst;
        }
    }
}

For an example of usage, we will create a singleton class that generates a sequence number:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Must seal the class so no sub-classes can be defined.
public sealed class SequenceGeneratorSingleton
    : SingletonBase<SequenceGeneratorSingleton>
{
    // Must have a private constructor so no instance can be created externally.
    SequenceGeneratorSingleton()
    {
        _number = 0;
    }
 
    private int _number;
 
    public int GetSequenceNumber()
    {
        return _number++;
    }
}

Then, a console application will call the sequence generator class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Sequence: " + SequenceGeneratorSingleton.Instance
            .GetSequenceNumber().ToString());  // Print "Sequence: 0"
 
        Console.WriteLine("Sequence: " + SequenceGeneratorSingleton.Instance
            .GetSequenceNumber().ToString());  // Print "Sequence: 1"
 
        Console.WriteLine("Sequence: " + SequenceGeneratorSingleton.Instance
            .GetSequenceNumber().ToString());  // Print "Sequence: 2"
 
        Console.ReadLine();
    }
}

To recap, in order to create a singleton class using the singleton base class, you need to do the following:

  1. Define a sealed class which derives from SingletonBase<T>, where T is the class name you are defining. It ensures that you cannot create subclasses from this singleton class.
  2. Define a single parameterless private constructor inside the class. It ensures that no instances of this class can be created externally.
  3. Access the class’ singleton instance and public members by calling the Instance property.

I have also included the code in LiquidSilver, which you can view or download from the repository.

Refreshing the LINQ to SQL DataContext by Clearing the Cache

LINQ to SQL DataContext can sometimes be difficult to deal with. Especially when combined with the use of stored procedures. For example, there is a case where I want to delete multiple records with a stored procedure rather than using the LINQ to SQL API for performance reason. After executing the stored procedure, the DataContext is not aware of the changes and still thinks that the entities are still there because the DataContext caches them. Hence, when I try to add another record using the same key, the DataContext throws an exception with the following message:

Cannot add an entity with a key that is already in use.

Logically, I want to refresh the DataContext memory so it will recheck the database. The provided DataContext.Refresh() method requires the original entity set to be sent which can be a problem. I don’t want to query the DataContext for the entities for performance reason, hence the stored procedure is used in the first place. So I have to find another way to refresh the DataContext or clear the cache without relying on the original entity set.

There is no official way to do it, but I stumbled on this blog post telling that there is a DataContext method called ClearCache() that can be used for that purpose. Unfortunately that method has internal modifier so you cannot call it from your code. But with a bit of reflection magic you can borrow the hidden power as follows:

context.GetType().InvokeMember(
	"ClearCache",
	BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
	null, context, null);

After invoking the ClearCache() method, I can now successfully add new entities to the DataContext by reusing the keys from the deleted records.

C# 4.0 and Dynamic Programming

In Microsoft PDC2008, Anders Hejlsberg — C# lead designer and Microsoft Technical Fellow — introduces the future of C#, dubbed C# 4.0. You can watch his recorded presentation at Channel 9. The following is a brief summary on dynamic programming, one of C# 4.0 new features.

C# Evolution

  • C# 1.0: Managed Code
  • C# 2.0: Generics
  • C# 3.0: Language Integrated Query
  • C# 4.0: Dynamic Programming

Nowadays, codes can reside in any kind of form, i.e., .NET objects, JavaScript, Python, Ruby, COM. In order to use the codes written in different form, currently we have some different approaches.

For example, to call a .NET object, we will write the following:

Calculator calc = GetCalculator();
int sum = calc.Add(10, 20);

Now we try to call a .NET object too, but we don’t know which class exactly having the code:

object calc = GetCalculator();
Type calcType = calc.GetType();
object res = calcType.InvokeMember("Add", BindingFlags.InvokeMethod, null, new object[] { 10, 20 });
int sum = Convert.ToInt32(res);

While this is for calling a JavaScript object:

ScriptObject calc = GetCalculator();
object res = calc.Invoke("Add", 10, 20);
int sum = Convert.ToInt32(res);

Observe that there are different procedures to call different objects. With C# 4.0 dynamic keyword, we can use this instead of all those above:

dynamic calc = GetCalculator();
int sum = calc.Add(10, 20);

The compiler will not check whether there is an “Add” method in the “calc” object. Instead, the DLR will bind the method call to the responsible object on runtime as shown in the following picture:

Dynamic Language Runtime

Anders stated that he did not have any intention to ask all developers to rewrite all their codes to be dynamic. In fact, he is a strong believer of static language strong features: statement completion, refactoring, compilation type check, and performance. But he also embraces the flexibility and productivity of dynamic languages such as Python and Ruby. And there are an increasing numbers of things that your application needs to talk to, that is not statically typed. You may need to talk to a JavaScript code, or maybe a Python or Ruby codes. The question is, should we make it painful to talk to them or make it easier?

For Anders, he wants the later. As LINQ intends to provide a unified way to access all kind of data source, dynamic in C# intends to provide a unified way to talk to all kind of codes, be it statically or dynamically typed.