Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

common Singleton Pattern implementation using Generic

2.67/5 (3 votes)
18 Oct 2011CPOL 21.9K  
Customized implementation of the Singleton pattern using Generics.
I read this link content(Jon Skeet) and implement the singleton pattern in a class that can be used for any object that you want to be singleton.

http://csharpindepth.com/Articles/General/Singleton.aspx[^]

Generic implementation of Jon Skeet's is here:
C#
public class Singleton<T> where T : new()
{
    private static readonly Lazy<T> lazy = new Lazy<T>(() => new T());

    Singleton()
    {
    }

    public static T Instance
    {
        get
        {
            return lazy.Value;
        }
    }
}


For example, we have a service:

C#
public class SampleService
{
    public List<MyItemType> GetItems()
    {
        var dataList = new List<MyItemType>();
        //do some works and fill dataList
        return dataList;
    }
}


Everywhere I want to use SampleService, I can get a singleton instance in this way:

C#
var serviceInstance = Singleton<sampleservice>.Instance;

var myList = serviceInstance.GetItems();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)