Click here to Skip to main content
Click here to Skip to main content
Go to top

common Singleton Pattern implementation using Generic

, 17 Oct 2011
Rate this:
Please Sign up or sign in to vote.
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.[^]
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());
        public static T Instance
                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();


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


About the Author

omid rezaei hanjani
Software Developer
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
No Biography provided

Comments and Discussions

GeneralReason for my vote of 4 good PinmemberJai Mallesh10-Oct-11 19:38 
GeneralProbably needs to be tagged as .Net 4 as it is using <code>L... PinmemberReiss5-Oct-11 3:30 
GeneralRe: thanks reiss, now its be tagged as .Net 4 too Pinmemberomid rezaei hanjani17-Oct-11 23:42 
Generalthanks richard, I changed that Pinmemberomid rezaei hanjani4-Oct-11 22:01 
GeneralThis code is not fool proof. If I wish, I can directly creat... PinmemberA. Rajesh Kumar3-Oct-11 20:21 
GeneralReason for my vote of 2 The phrase "my implementation" impli... PinmemberRichard Deeming3-Oct-11 9:59 
GeneralRe: Thanks Richard, I changed "my implementation" to "generic im... Pinmemberomid rezaei hanjani4-Oct-11 23:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 18 Oct 2011
Article Copyright 2011 by omid rezaei hanjani
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid