Static Constructor & Singleton class - c#

I have an object cache which implements the Singleton design pattern. My approach to singleton was always to lazy load the static instance when the property is first accessed.
public static Widget
{
get
{
if(instance==null) instance = new Widget();
return instance;
}
}
However, I know that this approach isn't thread safe and the check for instance being null introduces a small inefficiency. Would it be wise to implement a static constructor on the class which instantiates the static instance?
As I understand it, the static constructor would be called whenever the first static property access occurs. Is this valid, and will it provide any benefits over the current lazy load approach or would it be better to explore a proxy implementation, or use a lock to force it to be thread safe?
public static Widget
{
get
{
if(instance==null)
{
lock(padlock)
{
if(instance==null) instance = new Widget();
}
}
return instance;
}
}
I don't have a whole lot of experience with static constructors, so don't want to leap in with this idea if it is an equal or worse implementation of the lazy load property.
Cheers,
Gary

Jon Skeet has a nice article on singletons discussing this issue.

Rather than rolling your own threadsafe lazy initializer and possibly getting it wrong, I recommend reading the msdn on Lazy<T>.
https://learn.microsoft.com/en-us/dotnet/framework/performance/lazy-initialization#thread-safe-initialization

Related

Initializing Singleton Instance Inside Static Constructor

I want to implement simple Singleton and after some investigation have following to working fine. I test it using a simple console app but will be helpful if someone else can comment on it. The reason I've a doubt because new instance of Singleton is created within a static constructor and not sure if that's has any side effects.
sealed class SingletonEx
{
public static readonly SingletonEx Instance;
static SingletonEx()
{
if (null == Instance)
{
Instance = new SingletonEx();
}
}
private SingletonEx() { }
}
In case you're curious I found http://csharpindepth.com/Articles/General/Singleton.aspx quite helpful on this topic.
This is not a typical usage for static constructor, although it is possible to do so. Side effect would be that constructor would run before first using of any SingletonEx instance will be used in your code. Having a static constructor wouldn't change much about the "Singleton" behaviour. But, pay attention that initilization would happend in another stage than it would usually be if it wern't static.
I'd be worried for the following line:
public static readonly SingletonEx Instance;
Here are your problems:
public - Means it could be changed outside of the class.Because the Singleton instance is referenced by a private static member variable, the instantiation does not occur until the class is first referenced by a call to the Instance property. This solution therefore implements a form of the lazy instantiation property, as in the Design Patterns form of Singleton. When implement design pattern follow as much as you can on it's design.
readonly - shouldn't be here either. It is usually editable, unless you have a good reason for that.

Moving singleton definition into mixins in C#

I have to change around 10 classes into singletons and I thought that instead of copy-pasting the code it makes sense to use mixins, like it is described here: http://msdn.microsoft.com/en-us/vstudio/bb625996.aspx
However, I need not that much of additional methods, but more additional changes to the class itself, I have problems applying those instructions.
I tried to create an empty interface ISingleton and then to add the singleton part as extension to the new class public static class Singleton
This is singleton part which I would like to use:
public static SomeClass Instance
{
get { return _instance ?? (_instance = new SomeClass ()); }
}
private static SomeClass _instance;
But when adding it as extension I had a problem - how to define the Instance property, so it will be reusable by many classes?
And the second issue - I still need to change the constructors to private manually.
Does this approach makes any sense?
I haven't used mixins before, maybe this is just not the right scenario for it?
The mixins link you gave shows extension methods being used to add functionality to all objects supporting an interface. You still need to create the objects first. As singleton patterns handle the creation of objects it's basicly too soon to apply these techiniques.
Singleton needn't be so complicated, you're reading Jon Skeets article, a simple:
public sealed MyClass
{
private MyClass(){}
public static MyClass Instance = new MyClass();
}
Is often all you need. I'd happily repeat that code 10 times if needed. Or one can use a service locator or IoC container to manage the lifetime of objects.

Concise Singleton impl that supports reentrancy

I would like to find a concise C# implementation of the Singleton pattern, and I am wondering if it should support the following scenario. What if my singleton's private constructor, as part of initializing the instance, calls a constructor that itself tries to access the singleton currently being initialized? This is what I meant by reentrancy in this question's title. Some would say that a constructor shouldn't do anything complex enough that could lead to this occurring. But what if, due to some future code change within the invoked constructors, it does happen?
I looked through the various answers to this question. I am impressed by the brevity of using Lazy<T>. In the use case I am looking it, it throws an exception which is much better than constructing two instances of the singleton. But alas, in throwing the exception it crashes the app which means it does not support the target scenario.
class Apple
{
static readonly Lazy<Apple> instance = new Lazy<Apple>( () => new Apple(), true );
public static Apple Instance { get { return instance.Value; } }
private Apple()
{
// Call other methods which might access Instance...
var testGet = Instance;
}
}
So I have the idea to instead do the following.
class Banana
{
static Banana instance;
public static Banana Instance { get { return instance ?? new Banana(); } }
private Banana()
{
instance = this;
// Then call other methods which might access Instance...
var testGet = Instance;
}
}
It supports the target scenario, but is anything wrong with it? Is there a better solution?
Please note the following before posting an answer. Like many people, I still consider Singleton as a pattern. Many DI enthusiasts like calling it an anti-pattern. In the context of a project that relies on DI/IoC, this is a reasonable assertion. Outside of that context, however, Singleton is still a valid design pattern. I do not use DI and am not interested in discussing its merit points here. Please do not post an answer below if it will refer to Singleton as an "anti-pattern", or if it will offer "dependency injection" as the solution. Thanks in advance.
Although Singleton may not be considered an anti-pattern, accessing members of an instance before that instance is fully constructed is an anti-pattern. You can't guarantee that code external to the class being initialized doesn't try using some uninitialized state. So the scenario in question should not be supported. If code that attempts to access the singleton is later added to the constructors invoked by the singleton's constructor, then that should trigger a redesign.
Using Lazy<T> as Apple demonstrates is the better approach since it throws an exception on re-entrance rather than accessing an incomplete instance. Lazy<T> additionally supports access from multiple threads, if needed.

Difference between these two Singleton implementations

I am learning how to implement some basic design patterns. Whilst learning the Singleton pattern I have noticed that there are two common implementations on the web:
// Possibly from: http://www.yoda.arachsys.com/csharp/singleton.html
// I cannot remember exact source, sorry :(
public sealed class Singleton
{
// Static members are 'eagerly initialized', that is,
// immediately when class is loaded for the first time.
// .NET guarantees thread safety for static initialization
private static readonly Singleton instance = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() { }
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
public static Singleton() { }
// Get the instance of the singleton
public static Singleton getInstance()
{
return instance;
}
}
and:
public class Singleton
{
// Static, VOLATILE variable to store single instance
private static volatile Singleton m_instance;
// Static synchronization root object, for locking
private static object m_syncRoot = new object();
// Property to retrieve the only instance of the Singleton
public static Singleton Instance
{
get
{
// Check that the instance is null
if (m_instance == null)
{
// Lock the object
lock (m_syncRoot)
{
// Check to make sure its null
if (m_instance == null)
{
m_instance = new Singleton();
}
}
}
// Return the non-null instance of Singleton
return m_instance;
}
}
}
In what scenario would you opt to have eagerly initialized vs lazy initialized?
Is the comment in the first example correct in saying that the initialization is thread safe? (I know it says it is, but it's the internet...)
I definitely would go with your first implementation...
the second seems questionable to me... if you need/want a lazy implementation you could use Lazy<T> for that - since it is part of the framework it feels much more comfortable..
BTW: There are even more ways to implement the Singleton pattern... here is an excellent article.
I'm not sure but it looks like you got those examples from here: http://www.yoda.arachsys.com/csharp/singleton.html
If not, read through it. There are a couple of thoughts on the two versions.
If you ask me personally: I would go for the 2nd solution if I needed to know if the singleton has already been initialized or not.
If you don't have to deal with multithreading, I would use an even simpler approach (see the "Bad Code" examples in the references link).
The first one is safe and lazy.
static constructors are guaranteed to be executed only once, and immediately before the first access to Instrance. If there is a static constructor(even if empty) then static field initializations are guaranteed to execute directly before the static constructor. If there is no static constructor, field initialization may occur earlier.
The second one is lazy, but I'm not sure if the double-lock pattern is valid like this. I suspect that it is broken, at least in the ECMA memory model.
Personally I'd avoid any Class.Instance singleton pattern in favour of IoC singletons in most situations.
1) that's entirely a design choice. Init up front or init when required.
2) Yes, it is thread safe as the CLR guarantees single threaded object initialisation. (static and instance)
EDIT
personally, in the first example, I make the Instance field public and dispense with the getter. Be interested to know if there is any reason that this is a bad idea?
It's a singleton so I'd go for option 1, unless it's a massive object that's not always even needed. But I probably would not make a singleton for something that's often not used at all.
Both implementations are fine, so it depends on what you need.
If performance is not an issue, use the eagerly created instance of the first one. Otherwise, use the second one, in which only the first access is synchronized.

Two questions on Singleton C#

Consider the following code
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
static Singleton() {}
private Singleton() {}
}
Question
1) Here what is the purpose of static constructor ? (I know static constructor will be called before the first instance of the class is created).But in the context of above code
can't i use it without the static constructor?
2) I heard that one of the advantages of singleton is that it can be extended into factory.
Since it is a sealed class ,how will you extend it into factory?can you give some example?
The static constructor ensures that the singleton really isn't constructed before it's used. If the static constructor isn't present, the CLR has a lot more leeway about when it runs the type initializer. See my article on beforefieldinit and my blog post about .NET 4 type initialization changes for more info.
As for turning a singleton into a factory - you'd really have to give more context. Your Instance property could choose whether to always return a reference to the same object or not, I suppose...
There is no need for a static constructor. SKEET!
I've never heard of that. You can't, obviously, if the class is sealed. But you could moderately easily rewrite it as a factory, as there is only one way to instantiate it--through a property. Change that into a method, and you have the starts of a factory. The method may return the same instance each time, or may return an instance from a pool, or do whatever it wants.
I wouldn't suggest you have a factory property, as properties shouldn't be doing too much work.

Categories

Resources