Concise Singleton impl that supports reentrancy - c#

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.

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.

Do I need to use synclock with objects managed by a DI container using singleton scope?

I have the following code:
public class DotLessFactory
{
private LessEngine lessEngine;
public virtual ILessEngine GetEngine()
{
return lessEngine ?? (lessEngine = CreateEngine());
}
private ILessEngine CreateEngine()
{
var configuration = new LessConfiguration();
return new LessFactory().CreateEngine(configuration);
}
}
Let's assume the following:
I always want the same instance of ILessEngine to be returned.
I use a DI container (I will use StructureMap for this example) to manage my objects.
The lifetime of my objects will be Singleton because of assumption number 1.
The code inside CreateEngine executes code that is referenced through a NuGet package.
DotLess is a mere example. This code could be applicable to any similar NuGet package.
Approach 1
I register my objects with my DI container using:
For<DotLessFactory>().Singleton().Use<DotLessFactory>();
For<ILessEngine>().Singleton().Use(container => container.GetInstance<DotLessFactory>().GetEngine());
For<ISomeClass>().Singleton().Use<SomeClass>();
Now I can add ILessEngine to a constructor and have my container inject an instance of it as per the code below.
public class SomeClass : ISomeClass
{
private ILessEngine lessEngine;
public SomeClass(ILessEngine lessEngine)
{
this.lessEngine = lessEngine;
}
}
Approach 2
Introduce an IDotLessFactory interface which exposes the GetEngine method. I register my objects with my DI container using:
For<IDotLessFactory>().Singleton().Use<DotLessFactory>();
For<ISomeClass>().Singleton().Use<SomeClass>();
Now my factory will create an instance of ILessEngine as per the code below.
public class SomeClass : ISomeClass
{
private ILessEngine lessEngine;
public SomeClass(IDotLessFactory factory)
{
Factory = factory;
}
public IDotLessFactory Factory { get; private set; }
public ILessEngine LessEngine
{
get
{
return lessEngine ?? (lessEngine = Factory.GetEngine());
}
}
}
My questions are:
What is the fundamental difference between Approach 1 and 2 when it comes to ILessEngine? In approach 1 the ILessEngine is managed by the container and in approach 2 it is not. What are the upside/downside to each approach? Is one approach better than the other?
Do I need to use a synclock inside the CreateEngine method to ensure thread safety for any of the approaches? When should/shouldn't I use synclock in a scenario like this?
I have seen examples where Activator.CreateInstance is used inside the CreateEngine method as opposed to newing up the object directly. Is there a reason one would use this approach? Has this something to do with not introducing direct dependencies in the factory object to objects inside the NuGet package?
Let's assume the referenced NuGet package works with HttpContext under the hood. Would registering my factory in singleton scope have any negative effect on HttpContext or does that not matter since I assume the NuGet package most likely manages the scope of HttpContext itself?
Finally, the DotLessFactory will eventually be used with Bundles (Microsoft.AspNet.Web.Optimization NuGet package) and the Bundle is only instantiated (not managed by container) on Application Start. The Bundle will depend on an injected instance of DotLessFactory. Does this fact make any difference to the questions above?
Any feedback would be extremely helpful.
It's non-trivial to answer these questions specifically, but allow me to provide some non-exhaustive comments:
As far as I can tell, none of the approaches guarantee requirement #1 (singleton). This is because two threads could perform a look-up at the same time and both evaluate lessEngine to null and trigger the creation of a new instance. The first approach may end up being thread safe if StructureMap lookups are thread safe, but I'd be surprised if this was the case (and regardless, you do not want your code to depend on an implementation "detail" in a 3rd party library).
Both solutions make the same mistake, which is essentially checking whether an instance has already been created without protecting the entire code region. To solve the problem, introduce a private object variable to lock on, and protect the code region creating the instance:
private object engineLock = new object();
public virtual ILessEngine GetEngine()
{
lock( engineLock ) { return lessEngine ?? (lessEngine = CreateEngine()); }
}
As an aside, this would not be necessary if you could make StructureMap handle construction of the entire object chain, as it would then be up to StructureMap to ensure the singleton requirement as per your configuration of the container.
You can only new objects if you know they have a default constructor (e.g. through a generic constraint in the code for a type parameter) or you have a compile-time reference to them. Since an IoC mostly creates things it didn't know about at compile time, and it often needs to pass parameters when doing so, Activator.CreateInstance is used istead. As far as I know, using "new" generates IL to invoke Activator.CreateInstance, so the end result is all the same.
The lifetime of HttpContext is managed outside of your application (by ASP.NET) and so there is no scoping issue. HttpContext.Current will either be set or not, and if it isn't then you're doing work too early for it to be available (or executing in a context where it is never going to be available, e.g. outside ASP.NET).
Uh, not sure what potential problem you're considering here, but my best guess is that it shouldn't have any effect on your code.
Hope this helps!

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.

Possible to use a singleton with a non-default constructor in C#?

I'm implementing a notification framework for one of my projects. As i want it to be very generic, the user can use several transport layers, so that he doesn't really need to care about using one delivery method (lets say WCF) or another (for eg ActiveMQ).
The interface the user has access is of course independent of the delivery method (WCF or ActiveMQ).
Still, the two classes (consumer and producer) implements singletons, so they actually use default constructors (meaning, no parameters).
My problem is that i would like to have one parameter, the delivery method the user want to use.
But as far as i know, singleton only use default constructors? which is normal, as there should be no point of using singletons with parameters.
So, what are my options here? not to create a singleton? create a method to set the delivery method?
Thank you very much for your help,
Sebastian
You can certainly have parameters with singletons, except instead of passing the parameter into a constructor, you are passing it into the getInstance() method. Your overridden constructor needs to be private of course for a true singleton implementation. My example is written in Java but applies for C# as well.
Example:
Singleton s = Singleton.getInstance(42);
In the Singleton code:
private Singleton() {
}
private Singleton(int num) {
//set num
}
public getInstance(int num) {
//singleton code (calls the private non-default constructor if an object
//does not already exist)
}
There are some dependency injection frameworks like Spring.Net which might help you. You can effectively pass a parameter in a configuration file for your singletons constructor.
Link to a Spring Framework example
Might I suggest that if you have two different behaviours required of your singleton that you might want to subclass. That way you get the behaviour that you want by calling the singleton of the class behaviour you want.
You can do this easily with a dependency injection framework. I have a similar construct in my current project using MEF. All that's required is to use the constructor injection options, and add that assembly and the requested dependency's assembly to the catalog, and it wires it up correctly.
Another option is to have some form of initialize function that takes your option, and constructs the singleton instance. Instead of constructing it on first access, you can construct it during the initialization call. The downside here is that you need to make sure to initialize your singleton before you use it (typically at program start, using a config file).
A similar, but less error-prone option, is to just have the singleton lazy initialize, and give it a "default" option. Allow the caller to set a static property to alter which option is constructed, so if it's set prior to the singleton's construction, you'll get a different default. This can be confusing, though, since again, you need to make sure you set the property before accessing the singleton, or you'll get unexpected behavior.
I know it is late to answer the original question, but i just had this problem and here is how i solved it. Might not be ideal, but it seems to work.
I created a Init method that must be called before trying to use the singleton instance.
public void Init(/*parameters*/)
{
if (_isInitialized)
{
throw new InvalidOperationException("Component is already initialized!");
}
//do your work here
}
Any other access to the singleton instance (properties get, set, method calls) will throw an invalid operation exception telling that the object was not initialized.
I think this does what i need, is less confusing than GetInstance(params) because there is no risk of misunderstanding what the method does. The downside is it will not throw compilation time errors, but the first run without the initialization done will throw an exception, so it should be good enough.

Categories

Resources