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>();
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();