65.9K
CodeProject is changing. Read more.
Home

common Singleton Pattern implementation using Generic

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.67/5 (3 votes)

Sep 29, 2011

CPOL
viewsIcon

21900

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:
    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:
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:
var serviceInstance = Singleton<sampleservice>.Instance;

var myList = serviceInstance.GetItems();