As I go through the differences between Singleton Vs Static class, I came across one point that we can inherit an interface in singleton class and can call singleton through interface for multiple implementation.
I would like some code demonstration with good example, how object orientation can achieve through singleton and not through static.
Thanks,
Although it's hard to tell what exactly you are referring to, one pattern you might be referring to is the Multiton pattern, where you manage a map of named instances as key-value pairs.
That's basically a factory, but each instance is only created once:
I've modified the Wikipedia example a bit to show that you can even derive from a singleton class, as long as your concrete implementations are private and within the original class:
class FooMultiton
{
private static readonly Dictionary<object, FooMultiton> _instances =
new Dictionary<object, FooMultiton>();
// this is the classic good old singleton trick (prevent direct instantiation)
private FooMultiton()
{ }
// you can also have private concrete implementations,
// invisible to the outside world
private class ConcreteFooMultitonOne : FooMultiton
{ }
public static FooMultiton GetInstance(object key)
{
lock (_instances)
{
FooMultiton instance;
// if it doesn't exist, create it and store it
if (!_instances.TryGetValue(key, out instance))
{
// at this point, you can create a derived class instance
instance = new ConcreteFooMultitonOne();
_instances.Add(key, instance);
}
// always return the same ("singleton") instance for this key
return instance;
}
}
}
Also, generally, if a singleton is not a static class, it can implement any interface you want. The only thing that a singleton pattern prevents is instantiation of multiple instances of a singleton class, but that doesn't mean you cannot completely replace the implementation with something else.
For example, if you have a singleton which is not a static class:
interface ICanTalk
{
string Talk();
}
class Singleton : ICanTalk
{
private Singleton() { }
private static readonly Singleton _instance = new Singleton();
public static Singleton Instance
{ get { return _instance; } }
public string Talk()
{ return "this is a singleton"; }
}
You can also have a number of different implementations:
class OtherInstance : ICanTalk
{
public string Talk()
{ return "this is something else"; }
}
Then you are free to choose any implementation you want, but get only a single instance of the Singleton class:
ICanTalk item;
item = Singleton.Instance;
item = new OtherInstance();
item = new YetAnotherInstance();
According to nkr1pr
Every class can implement an interface, and a Singleton is just a "normal" class that makes sure that only one instance of it exists at any point in time apart from the other business logic it may implement. This also means that a Singleton has at least 2 responsibities and this is not good OO design as classes should only have 1 responsibility and make sure they are good at that responsibility, but that is another discussion.
Something like:
public interface MyInterface
{
}
And
public class MySingleton:MyInterface
{
private static MyInterface instance = new MySingleton();
private MySingleton()
{
}
public static MyInterface getInstance()
{
return instance;
}
}
I'm not sure what you are asking, but singleton classes can implement interfaces.
singleton class does not mean static class, one of the method to create a singleton instance is
to make use of static members.
public class MyInterfaceImplementation : IMyInterface
{
private static MyInterfaceImplementation instance;
private static readonly object lockObj = new object();
private MyInterfaceImplementation() { } //private .ctor
public static MyInterfaceImplementation Instance
{
get
{
if (instance == null)
{
lock (lockObj)
{
instance = new MyInterfaceImplementation();
}
}
return instance;
}
}
public void MyInterfaceMethod()
{
//Implement here
}
}
Singleton implemented with C# could be like:
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
If I use static to implement it like:
public static class Globals{
public static Singleton Instance = new Singleton();
}
in this way, app should also only get the one instance for the entire app.
So what's the difference between these 2 approaches? Why not use static member directly(more simple and straight forward)?
If you use the second approach:
public static class Globals{
public static Singleton Instance = new Singleton();
}
There's nothing preventing somebody from doing:
Singleton anotherInstance = new Singleton(); // Violates singleton rules
You also don't get the same lazy initialization your first version (attempts to) achieve, plus you're using a public field, which doesn't allow you the same flexibility in the future if you need to change what happens when a value is fetched.
Note that .NET 4 provides a potentially better approach to making a singleton:
public class Singleton
{
private static readonly Lazy<Singleton> instance = new Lazy<Singleton>( ()=> new Singleton());
private Singleton() {}
public static Singleton Instance
{
get
{
return instance.Value;
}
}
}
This is nice because it's fully lazy and fully thread safe, but also simple.
Below are some differences between static and Singleton :
Singleton is a pattern while static is a keyword.
Singleton class can have static and non static method, but static class can have only static members and methods.
We can implement interface in a Singleton class but in static class we cannot implement interface.
We can extend the Singleton class while we static class we can’t, i.e. Singleton class can be derived from any type of class.
for more static vs Singleton
I have a class which is lazy instantiated by another library. I don't have control over that library code but still need to be sure it cannot create more than one instance of my class.
Is it possible ? how ?
Some simple solutions to this question hides some problems, for a full understanding of this matter I recommend the reading of the following article
http://www.yoda.arachsys.com/csharp/singleton.html
Which concludes with an optimal solution
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
If it's calling your class's constructor, the only thing you can do is throw an exception in the constructor if you determine that an instance was previously created. Since you don't have control over the other library, you wouldn't be able to use a factory method or static property which would normally be the way you control access to a singleton.
Depending on your situation, you may also look into using a lightweight proxy that wraps a singleton instance. In this example, any number of MyObjectProxy can be created but they all defer their implementation to a single instance of MyObject.
public class MyObject {
internal MyObject() {
}
private int _counter;
public int Increment() {
return Interlocked.Increment(ref _counter);
}
}
public class MyObjectProxy {
private static readonly MyObject _singleton = new MyObject();
public MyObjectProxy() {
}
public int Increment() {
return _singleton.Increment();
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I need to store a bunch of variables that need to be accessed globally and I'm wondering if a singleton pattern would be applicable. From the examples I've seen, a singleton pattern is just a static class that can't be inherited. But the examples I've seen are overly complex for my needs. What would be the very simplest singleton class? Couldn't I just make a static, sealed class with some variables inside?
Typically a singleton isn't a static class - a singleton will give you a single instance of a class.
I don't know what examples you've seen, but usually the singleton pattern can be really simple in C#:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
static Singleton() {} // Make sure it's truly lazy
private Singleton() {} // Prevent instantiation outside
public static Singleton Instance { get { return instance; } }
}
That's not difficult.
The advantage of a singleton over static members is that the class can implement interfaces etc. Sometimes that's useful - but other times, static members would indeed do just as well. Additionally, it's usually easier to move from a singleton to a non-singleton later, e.g. passing in the singleton as a "configuration" object to dependency classes, rather than those dependency classes making direct static calls.
Personally I'd try to avoid using singletons where possible - they make testing harder, apart from anything else. They can occasionally be useful though.
There are several Patterns which might be appropriate for you, a singleton is one of the worse.
Registry
struct Data {
public String ProgramName;
public String Parameters;
}
class FooRegistry {
private static Dictionary<String, Data> registry = new Dictionary<String, Data>();
public static void Register(String key, Data data) {
FooRegistry.registry[key] = data;
}
public static void Get(String key) {
// Omitted: Check if key exists
return FooRegistry.registry[key];
}
}
Advantages
Easy to switch to a Mock Object for automated testing
You can still store multiple instances but if necessary you have only one instance.
Disadvantages
Slightly slower than a Singleton or a global Variable
Static Class
class GlobalStuff {
public static String ProgramName {get;set;}
public static String Parameters {get;set;}
private GlobalStuff() {}
}
Advantages
Simple
Fast
Disadvantages
Hard to switch dynamically to i.e. a Mock Object
Hard to switch to another object type if requirements change
Simple Singleton
class DataSingleton {
private static DataSingleton instance = null;
private DataSingleton() {}
public static DataSingleton Instance {
get {
if (DataSingleton.instance == null) DataSingleton.instance = new DataSingleton();
return DataSingleton;
}
}
}
Advantages
None really
Disadvantages
Hard to create a threadsafe singleton, the above Version will fail if multiple threads access the instance.
Hard to switch for a mock object
Personally I like the Registry Pattern but YMMV.
You should take a look at Dependency Injection as it's usually considered the best practice but it's too big a topic to explain here:
Dependency Injection
A Singleton isn't just a static class that can't be inherited. It's a regular class that can be instantiated only once, with everybody sharing that single instance (and making it thread safe is even more work).
The typical .NET code for a Singleton looks something like the following. This is a quick example, and not by any means the best implementation or thread-safe code:
public sealed class Singleton
{
Singleton _instance = null;
public Singleton Instance
{
get
{
if(_instance == null)
_instance = new Singleton();
return _instance;
}
}
// Default private constructor so only we can instanctiate
private Singleton() { }
// Default private static constructor
private static Singleton() { }
}
If you're going to go down the path you're thinking, a static sealed class will work just fine.
Using C# 6 Auto-Property Initializers.
public sealed class Singleton
{
private Singleton() { }
public static Singleton Instance { get; } = new Singleton();
}
Short and clean - I'll be happy to hear the downsides.
I know this Issue is old, but here is another solution using .Net 4.0 or later (including .Net Core and .Net Standard).
First, define your class that will be transformed into a Singleton:
public class ClassThatWillBeASingleton
{
private ClassThatWillBeASingleton()
{
Thread.Sleep(20);
guid = Guid.NewGuid();
Thread.Sleep(20);
}
public Guid guid { get; set; }
}
In this Example Class I've defined one constructor that Sleeps for a while, and then creates one new Guid and save to it's public property. (The Sleep is just for concurrency testing)
Notice that the constructor is private, so that no one can create a new instance of this class.
Now, We need to define the wrapper that will transform this class into a singleton:
public abstract class SingletonBase<T> where T : class
{
private static readonly Lazy<T> _Lazy = new Lazy<T>(() =>
{
// Get non-public constructors for T.
var ctors = typeof(T).GetConstructors(System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic);
if (!Array.Exists(ctors, (ci) => ci.GetParameters().Length == 0))
throw new InvalidOperationException("Non-public ctor() was not found.");
var ctor = Array.Find(ctors, (ci) => ci.GetParameters().Length == 0);
// Invoke constructor and return resulting object.
return ctor.Invoke(new object[] { }) as T;
}, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
public static T Instance
{
get { return _Lazy.Value; }
}
}
Notice that it uses Lazy to create a field _Lazy that knows how to instantiate a class using it's private constructor.
And it defines one Property Instance to access the Value of the Lazy field.
Notice the LazyThreadSafetyMode enum that is passed to the Lazy constructor. It is using ExecutionAndPublication. So only one thread will be allowed to initialize the Value of the Lazy field.
Now, all we have to do is define the wrapped class that will be a singleton:
public class ExampleSingleton : SingletonBase<ClassThatWillBeASingleton>
{
private ExampleSingleton () { }
}
Here is one example of the usage:
ExampleSingleton.Instance.guid;
And one test to assert that two threads will get the same instance of the Singleton:
[Fact()]
public void Instance_ParallelGuid_ExpectedReturnSameGuid()
{
Guid firstGuid = Guid.Empty;
Guid secondGuid = Guid.NewGuid();
Parallel.Invoke(() =>
{
firstGuid = Singleton4Tests.Instance.guid;
}, () =>
{
secondGuid = Singleton4Tests.Instance.guid;
});
Assert.Equal(firstGuid, secondGuid);
}
This test is calling the Value of the Lazy field concurrently, and we want to assert that both instances that will be returned from this property (Value of Lazy) are the same.
More details about this subject can be found at: C# in Depth
So, as far as I am concerned, this is the most concise and simple implementation of the Singleton pattern in C#.
http://blueonionsoftware.com/blog.aspx?p=c6e72c38-2839-4696-990a-3fbf9b2b0ba4
I would, however, suggest that singletons are really ugly patterns... I consider them to be an anti-pattern.
http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx
For me, I prefer to have something like a Repository, implementing IRepository. Your class can declare the dependency to IRepository in the constructor and it can be passed in using Dependency Injection or one of these methods:
http://houseofbilz.com/archive/2009/05/02.aspx
Use your language features.
Mostly simple thread-safe implementation is:
public sealed class Singleton
{
private static readonly Singleton _instance;
private Singleton() { }
static Singleton()
{
_instance = new Singleton();
}
public static Singleton Instance
{
get { return _instance; }
}
}
...what would be the very simplest singleton class?
Just to add one more possible solution. The simplest, most straight forward and easy to use approach I can think of would be something like this:
//The abstract singleton
public abstract class Singleton<T> where T : class
{
private static readonly Lazy<T> instance = new Lazy<T>( CreateInstance, true );
public static T Instance => instance.Value;
private static T CreateInstance()
{
return (T)Activator.CreateInstance( typeof(T), true);
}
}
//This is the usage for any class, that should be a singleton
public class MyClass : Singleton<MyClass>
{
private MyClass()
{
//Code...
}
//Code...
}
//Example usage of the Singleton
class Program
{
static void Main(string[] args)
{
MyClass clazz = MyClass.Instance;
}
}
I have the following C# singleton pattern, is there any way of improving it?
public class Singleton<T> where T : class, new()
{
private static object _syncobj = new object();
private static volatile T _instance = null;
public static T Instance
{
get
{
if (_instance == null)
{
lock (_syncobj)
{
if (_instance == null)
{
_instance = new T();
}
}
}
return _instance;
}
}
public Singleton()
{ }
}
Preferred usage example:
class Foo : Singleton<Foo>
{
}
Related:
An obvious singleton implementation for .NET?
According to Jon Skeet in Implementing the Singleton Pattern in C# the code you posted is actually considered as bad code, because it appears broken when checked against the ECMA CLI standard.
Also watch out: everytime you instantiate your object with a new type of T, it becomes another instance; it doesn't get reflected in your original singleton.
This code won't compile, you need "class" constraint on T.
Also, this code requires public constructor on target class, which is not good for singleton, because you can't control at compile time that you obtain (single) instance only via Instance property (or field). If you don't have any other static members except Instance, you are ok to go with just this:
class Foo
{
public static readonly Instance = new Foo();
private Foo() {}
static Foo() {}
}
It is thread safe (guaranteed by CLR) and lazy (instance is created with first access to type). For more discussion about BeforeFieldInit and why we need static constructor here, see https://csharpindepth.com/articles/BeforeFieldInit.
If you want to have other public static members on type, but create object only on access to Instance, you may create nested type, like in https://csharpindepth.com/articles/Singleton
Courtesy of Judith Bishop, http://patterns.cs.up.ac.za/
This singleton pattern implementation ensures lazy initialisation.
// Singleton PatternJudith Bishop Nov 2007
// Generic version
public class Singleton<T> where T : class, new()
{
Singleton() { }
class SingletonCreator
{
static SingletonCreator() { }
// Private object instantiated with private constructor
internal static readonly T instance = new T();
}
public static T UniqueInstance
{
get { return SingletonCreator.instance; }
}
}
This is my point using .NET 4
public class Singleton<T> where T : class, new()
{
Singleton (){}
private static readonly Lazy<T> instance = new Lazy<T>(()=> new T());
public static T Instance { get { return instance.Value; } }
}
I don't think that you really want to "burn your base class" so that you can save 2 lines of code. You don't really need a base class to implement singleton.
Whenever you need a singleton, just do this:
class MyConcreteClass
{
#region Singleton Implementation
public static readonly Instance = new MyConcreteClass();
private MyConcreteClass(){}
#endregion
/// ...
}
More details on this answer on a different thread : How to implement a singleton in C#?
However the thread doesn't use generic.
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
There's no ambiguity in .NET around initialization order; but this raises threading issues.
:/ The generic "singleton" pattern by Judith Bishop seems kinda flawed, its always possible to create several instances of type T as the constructor must be public to use it in this "pattern". In my opinion it has absolutely nothing to do with singleton, its just a kind of factory, which always returns the same object, but doesn't make it singleton... as long as there can be more than one instance of a class it can't be a singleton. Any reason this pattern is top-rated?
public sealed class Singleton
{
private static readonly Singleton _instance = new Singleton();
private Singleton()
{
}
public static Singleton Instance
{
get
{
return _instance;
}
}
}
Static initializers are considered thread-safe.. I don't know but you shouldn't use idioms of singleton at all, if you wrap my code above its not more than 3 lines... and inheriting from a singleton doesn't make any sense either.
I was looking for a better Singleton pattern and liked this one. So ported it to VB.NET, can be useful for others:
Public MustInherit Class Singleton(Of T As {Class, New})
Public Sub New()
End Sub
Private Class SingletonCreator
Shared Sub New()
End Sub
Friend Shared ReadOnly Instance As New T
End Class
Public Shared ReadOnly Property Instance() As T
Get
Return SingletonCreator.Instance
End Get
End Property
End Class
As requested, cross posting from my original answer to another question.
My version uses Reflection, works with non-public constructors in the derived class, is threadsafe (obviously) with lazy instantiation (according to the article I found linked below):
public class SingletonBase<T> where T : class
{
static SingletonBase()
{
}
public static readonly T Instance =
typeof(T).InvokeMember(typeof(T).Name,
BindingFlags.CreateInstance |
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic,
null, null, null) as T;
}
I picked this up a few years ago, not sure how much is mine, but googling on the code might find the original source of the technique if it wasn't me.
This is the oldest source of the code that I can find that was not me posting it.
Try this generic Singleton class implementing the Singleton design pattern in a thread safe and lazy way (thx to wcell).
public abstract class Singleton<T> where T : class
{
/// <summary>
/// Returns the singleton instance.
/// </summary>
public static T Instance
{
get
{
return SingletonAllocator.instance;
}
}
internal static class SingletonAllocator
{
internal static T instance;
static SingletonAllocator()
{
CreateInstance(typeof(T));
}
public static T CreateInstance(Type type)
{
ConstructorInfo[] ctorsPublic = type.GetConstructors(
BindingFlags.Instance | BindingFlags.Public);
if (ctorsPublic.Length > 0)
throw new Exception(
type.FullName + " has one or more public constructors so the property cannot be enforced.");
ConstructorInfo ctorNonPublic = type.GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], new ParameterModifier[0]);
if (ctorNonPublic == null)
{
throw new Exception(
type.FullName + " doesn't have a private/protected constructor so the property cannot be enforced.");
}
try
{
return instance = (T)ctorNonPublic.Invoke(new object[0]);
}
catch (Exception e)
{
throw new Exception(
"The Singleton couldnt be constructed, check if " + type.FullName + " has a default constructor", e);
}
}
}
}
The Double-Check Locking [Lea99] idiom provided by Microsoft here is amazingly similar to your provided code, unfortunately, this fails the ECMA CLI standard for a puritan view of thread-safe code and may not work correctly in all situations.
In a multi-threaded program, different threads could try to instantiate a class simultaneously. For this reason, a Singleton implementation that relies on an if statement to check whether the instance is null will not be thread-safe. Don't write code like that!
A simple, yet effective means of creating a thread-safe singleton is to use a nested class to instantiate it. The following is an example of a lazy instantiation singleton:
public sealed class Singleton
{
private Singleton() { }
public static Singleton Instance
{
get
{
return SingletonCreator.instance;
}
}
private class SingletonCreator
{
static SingletonCreator() { }
internal static readonly Singleton instance = new Singleton();
}
}
Usage:
Singleton s1 = Singleton.Instance;
Singleton s2 = Singleton.Instance;
if (s1.Equals(s2))
{
Console.WriteLine("Thread-Safe Singleton objects are the same");
}
Generic Solution:
public class Singleton<T>
where T : class, new()
{
private Singleton() { }
public static T Instance
{
get
{
return SingletonCreator.instance;
}
}
private class SingletonCreator
{
static SingletonCreator() { }
internal static readonly T instance = new T();
}
}
Usage:
class TestClass { }
Singleton s1 = Singleton<TestClass>.Instance;
Singleton s2 = Singleton<TestClass>.Instance;
if (s1.Equals(s2))
{
Console.WriteLine("Thread-Safe Generic Singleton objects are the same");
}
Lastly, here is a somewhat releated and usefull suggestion - to help avoid deadlocks that can be caused by using the lock keyword, consider adding the following attribute to help protect code in only public static methods:
using System.Runtime.CompilerServices;
[MethodImpl (MethodImplOptions.Synchronized)]
public static void MySynchronizedMethod()
{
}
References:
C# Cookbook (O'Reilly), Jay Hilyard & Stephen Teilhet
C# 3.0 Design Patterns (O'Reilly), Judith Bishop
CSharp-Online.Net - Singleton design pattern: Thread-safe Singleton
I quite liked your original answer - the only thing missing (according to the link posted by blowdart) is to make the _instance variable volatile, to make sure it has actually been set in the lock.
I actually use blowdarts solution when I have to use a singleton, but I dont have any need to late-instantiate etc.
My contribution for ensuring on demand creation of instance data:
/// <summary>Abstract base class for thread-safe singleton objects</summary>
/// <typeparam name="T">Instance type</typeparam>
public abstract class SingletonOnDemand<T> {
private static object __SYNC = new object();
private static volatile bool _IsInstanceCreated = false;
private static T _Instance = default(T);
/// <summary>Instance data</summary>
public static T Instance {
get {
if (!_IsInstanceCreated)
lock (__SYNC)
if (!_IsInstanceCreated)
_Instance = Activator.CreateInstance<T>();
return _Instance;
}
}
}
pff... again... :)
My contribution for ensuring on demand creation of instance data:
/// <summary>Abstract base class for thread-safe singleton objects</summary>
/// <typeparam name="T">Instance type</typeparam>
public abstract class SingletonOnDemand<T> {
private static object __SYNC = new object();
private static volatile bool _IsInstanceCreated = false;
private static T _Instance = default(T);
/// <summary>Instance data</summary>
public static T Instance {
get {
if (!_IsInstanceCreated)
lock (__SYNC)
if (!_IsInstanceCreated) {
_Instance = Activator.CreateInstance<T>();
_IsInstanceCreated = true;
}
return _Instance;
}
}
}
public static class LazyGlobal<T> where T : new()
{
public static T Instance
{
get { return TType.Instance; }
}
private static class TType
{
public static readonly T Instance = new T();
}
}
// user code:
{
LazyGlobal<Foo>.Instance.Bar();
}
Or:
public delegate T Func<T>();
public static class CustomGlobalActivator<T>
{
public static Func<T> CreateInstance { get; set; }
}
public static class LazyGlobal<T>
{
public static T Instance
{
get { return TType.Instance; }
}
private static class TType
{
public static readonly T Instance = CustomGlobalActivator<T>.CreateInstance();
}
}
{
// setup code:
// CustomGlobalActivator<Foo>.CreateInstance = () => new Foo(instanceOf_SL_or_IoC.DoSomeMagicReturning<FooDependencies>());
CustomGlobalActivator<Foo>.CreateInstance = () => instanceOf_SL_or_IoC.PleaseResolve<Foo>();
// ...
// user code:
LazyGlobal<Foo>.Instance.Bar();
}
Saw one a while ago which uses reflection to access a private (or public) default constructor:
public static class Singleton<T>
{
private static object lockVar = new object();
private static bool made;
private static T _singleton = default(T);
/// <summary>
/// Get The Singleton
/// </summary>
public static T Get
{
get
{
if (!made)
{
lock (lockVar)
{
if (!made)
{
ConstructorInfo cInfo = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);
if (cInfo != null)
_singleton = (T)cInfo.Invoke(new object[0]);
else
throw new ArgumentException("Type Does Not Have A Default Constructor.");
made = true;
}
}
}
return _singleton;
}
}
}
I submit this to the group. It seems to be thread-safe, generic and follows the pattern. You can inherit from it. This is cobbled together from what others have said.
public class Singleton<T> where T : class
{
class SingletonCreator
{
static SingletonCreator() { }
internal static readonly T Instance =
typeof(T).InvokeMember(typeof(T).Name,
BindingFlags.CreateInstance |
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic,
null, null, null) as T;
}
public static T Instance
{
get { return SingletonCreator.Instance; }
}
}
Intended implementation:
public class Foo: Singleton<Foo>
{
private Foo() { }
}
Then:
Foo.Instance.SomeMethod();
As in wikipedia:
the singleton pattern is a design pattern that restricts the
instantiation of a class to one object
I beleave that there is no guaranteed way to do it using generics, if you have restricted the instantiation of the singleton itself, how to restrict the instantiation of the main class, I think it is not possible to do that, and implementing this simple pattern is not that hard, take this way using the static constructor and private set:
public class MyClass
{
private MyClass()
{
}
static MyClass()
{
Instance = new MyClass();
}
public static MyClass Instance { get; private set; }
}
OR:
public class MyClass
{
private MyClass()
{
}
static MyClass()
{
Instance = new MyClass();
}
private static MyClass instance;
public static MyClass Instance
{
get
{
return instance;
}
private set
{
instance = value;
}
}
}
This works for me:
public static class Singleton<T>
{
private static readonly object Sync = new object();
public static T GetSingleton(ref T singletonMember, Func<T> initializer)
{
if (singletonMember == null)
{
lock (Sync)
{
if (singletonMember == null)
singletonMember = initializer();
}
}
return singletonMember;
}
}
Usage:
private static MyType _current;
public static MyType Current = Singleton<MyType>.GetSingleton(ref _current, () => new MyType());
Consume the singleton:
MyType.Current. ...
No Matter which exmaple you choose, always check for concurrency using Parallel.For!
( loop in which iterations may run in parallel)
put in Singleton C'tor :
private Singleton ()
{
Console.WriteLine("usage of the Singleton for the first time");
}
put in Main :
Parallel.For(0, 10,
index => {
Thread tt = new Thread(new ThreadStart(Singleton.Instance.SomePrintMethod));
tt.Start();
});
In many solutions today, people use service lifetime of singleton with dependency injection, as .NET offers this out of the box. If you still want to create a generic singleton pattern in your code where you might also consider initializing the type T to a initialized singleton object, 'settable once' and thread safe, here is a possible way to do it.
public sealed class Singleton<T> where T : class, new()
{
private static Lazy<T> InstanceProxy
{
get
{
if (_instanceObj?.IsValueCreated != true)
{
_instanceObj = new Lazy<T>(() => new T());
}
return _instanceObj;
}
}
private static Lazy<T>? _instanceObj;
public static T Instance { get { return InstanceProxy.Value; } }
public static void Init(Lazy<T> instance)
{
if (_instanceObj?.IsValueCreated == true)
{
throw new ArgumentException($"A Singleton for the type <T> is already set");
}
_instanceObj = instance ?? throw new ArgumentNullException(nameof(instance));
}
private Singleton()
{
}
}
The class is sealed and with a private constructor, it accepts types which are classes and must offer a public parameterless constructor 'new'. It uses the Lazy to achieve built in thread safety. You can init also the type T Singleton object for convenience. It is only allowed if a Singleton is not first set. Obviously, you should only init a Singleton of type T early on in your program, such as when the application or service / API starts up. The code will throw an ArgumentException if the Init method is called twice or more times for the type T.
You can use it like this :
Some model class :
public class Aeroplane
{
public string? Model { get; set; }
public string? Manufacturer { get; set; }
public int YearBuilt { get; set; }
public int PassengerCount { get; set; }
}
Usage sample :
var aeroplane = new Aeroplane
{
Manufacturer = "Boeing",
Model = "747",
PassengerCount = 350,
YearBuilt = 2005
};
var aeroPlane3 = Singleton<Aeroplane>.Instance;
var aeroPlane4 = Singleton<Aeroplane>.Instance;
Console.WriteLine($"Aeroplane3 and aeroplane4 is same object? {Object.ReferenceEquals(aeroPlane3, aeroPlane4)}");
Outputs 'true'.
Trying to re-init type T Singleton to another object fails :
var aeroplane2 = new Aeroplane
{
Manufacturer = "Sopwith Aviation Company",
Model = "Sophwith Camel",
PassengerCount = 1,
YearBuilt = 1917
};
Singleton<Aeroplane>.Init(new Lazy<Aeroplane>(aeroplane2));
You can of course just access the Singleton with initing it - it will call the default public constructor. Possible you could have a way of setting a custom constructor here instead of passing an object as a sort of 'factory pattern'.
var aeroplaneDefaultInstantiated = Singleton<Aeroplane>.Instance;
Default instantiation - calls the parameterless public constructor of type T.
You don't need all that, C# already has a good singleton pattern built-in.
static class Foo
If you need anything more interesting than that, chances are your new singleton is going to be just different enough that your generic pattern is going to be useless.
EDIT: By "anything more interesting" I'm including inheritance. If you can inherit from a singleton, it isn't a singleton any more.