Implement Singleton ... With Lock? - c#

On a multithread application (ASP.NET MVC) I need to have a global settings class which contains constants and values taken from Web.Config.
I would like to have this class static, as singleton ... And locked?
public static class Settings {
public static LoggerSettings Logger;
public static MailerSettings Mailer;
public class LoggerSettings {
public String Levels { get { return ConfigurationManager.AppSettings["Logger.Levels"]; } }
public const String Report = "team#xyz.com";
} // LoggerSettings
public class MailerSettings {
public String Contact { get { return ConfigurationManager.AppSettings["Mailer.Contact"]; } }
} // MailerSettings
}
I think I should implement a double lock? No?
I am not sure the best way to do this. Could I, please, get some help?
Thank You,
Miguel

I would like to have this class static, as singleton
To implement a singleton correctly in C#, see Jon Skeet's excellent summary of what does and does not work:
http://csharpindepth.com/Articles/General/Singleton.aspx
I think I should implement a double lock? No?
No. Double-checked locking is a low-lock technique and therefore insanely dangerous on weak memory model hardware. The moment you stray even the slightest from a "blessed" pattern you have abandoned all hope of the program behaving predictably.
The only circumstances under which I would use double-checked locking are when all of the following are true:
Is there is extensive empirical evidence that single-checked locking produces poor performance?
Let's suppose single-checked performance is unacceptable. Single-checked locking usually produces bad performance due to contention, so step one is eliminate the contention. Can you eliminate the contention and get acceptable performance? I would only use double-checked locking if it was impossible to remove the contention or if the performance problem was caused by the several nanoseconds it takes to obtain an uncontended lock. In the latter case: wow, that's a fast program that those nanoseconds are the slowest thing, and wow, you have pretty serious performance requirements if you're counting individual nanoseconds.
Let's suppose that single-checked performance is unacceptable and cannot be fixed. Is there another low-lock technique, like using Interlocked.CompareExchange or Lazy<T> that has acceptable performance? At least you know that CompareExchange and Lazy<T> were written by experts and enforce memory barriers appropriately on all hardware. Don't use double-checked locking if there is a better tool already implemented.
Let's suppose that none of these tools give acceptable performance. Does double-checked locking give acceptable performance? If not then don't use it.

as I see, you only read the data. So you need not lock here IMO.
Use static constructor to init your variables, like Report (made it also static).

Take a look at Jon Skeet's article Implementing the Singleton Pattern in C#
Simplest and good enough option:
public sealed class Settings
{
private static readonly Settings instance = new Settings();
public LoggerSettings Logger { get; private set; }
public MailerSettings Mailer { get; private set; }
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Settings()
{
}
private Settings()
{
Logger = new LoggerSettings();
Mailer = new MailerSettings();
}
public static Settings Instance { get { return instance;} }
}
public class LoggerSettings {
public LoggerSettings()
{
Levels = ConfigurationManager.AppSettings["Logger.Levels"];
}
public String Levels { get; private set; }
public const String Report = "team#xyz.com";
}
// Mailer settings would look similar
As you are only reading data from this instance you don't need any locking. The singleton instance is created before any other thread can access it so no need to lock there also.
Usage:
Settings.Instance.Mailer.Contact

if you like it static and as Singleton, try it this way:
public static class Settings {
private static readonly object LockObject = new object();
private static LoggerSetting LoggerInstance;
public static LoggerSetting LoggerSettings {
get {
lock (LockObject) {
if (LoggerInstance == null)
LoggerInstance = new LoggerInstance();
return LoggerInstance;
}
}
}
public class LoggerSetting {
public String Levels {
get { return ConfigurationManager.AppSettings["Logger.Levels"]; }
}
public const String Report = "team#xyz.com";
}
}
and use it by:
string x = Settings.LoggerSEttings.Report;

if you'd still like to go ahead and have a singleton instance
public class MySettings{
private static Object lockObj = new Object();
private MySettings() {} // private .ctor
private static MySettings _instance;
public static MySettings MySingleSettings{
get{
if(_instance == null){
lock(lockObj){
if(_instance == null)
_instance = new MySettings();
}
}
return _instance;
}
}

Related

Can a Class be Self-Referential?

I know this is sort of an odd thing, and I don't believe that I'm going to go this route because it seems ridiculous and because I have a better alternative, but...
Can a class be self-referential? Can it contain an instance of itself? It compiles (at least in MonoDevelop), but I have to imagine there's wide potential for issues.
The code in question is:
public class DamageVehicle
{
public int DVehicleID {get; set;}
}
public class DamageTypeArray
{
public int[] DTypeArray {get; set;}
}
public class DamagePackage
{
DamageVehicle dv;
DamageTypeArray dta;
DamagePackage dp;
}
Are there definite (non-opinion-based) reasons why this won't work in C#? Assuming at some level, dp = NULL, it won't iterate over itself forever, though it appears to have the potential to do so. What other issues can stem from this usage?
It doesn't contain itself itself, it holds a reference to itself.
Yes, there is nothing wrong with this. A reference is essentially just a pointer, and this is exactly how linked lists are implemented.
Not only it's possible, it's not rare for it to be used in practice, a good example is the Singleton pattern:
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}

Is there any issue with creating singleton following way in .Net ? [duplicate]

Isn't this a simpler as well as safe (and hence better) way to implement a singleton instead of doing double-checked locking mambo-jambo? Any drawbacks of this approach?
public class Singleton
{
private static Singleton _instance;
private Singleton() { Console.WriteLine("Instance created"); }
public static Singleton Instance
{
get
{
if (_instance == null)
{
Interlocked.CompareExchange(ref _instance, new Singleton(), null);
}
return _instance;
}
}
public void DoStuff() { }
}
EDIT: the test for thread-safety failed, can anyone explain why? How come Interlocked.CompareExchange isn't truly atomic?
public class Program
{
static void Main(string[] args)
{
Parallel.For(0, 1000000, delegate(int i) { Singleton.Instance.DoStuff(); });
}
}
Result (4 cores, 4 logical processors)
Instance created
Instance created
Instance created
Instance created
Instance created
If your singleton is ever in danger of initializing itself multiple times, you have a lot worse problems. Why not just use:
public class Singleton
{
private static Singleton instance=new Singleton();
private Singleton() {}
public static Singleton Instance{get{return instance;}}
}
Absolutely thread-safe in regards to initialization.
Edit: in case I wasn't clear, your code is horribly wrong. Both the if check and the new are not thread-safe! You need to use a proper singleton class.
You may well be creating multiple instances, but these will get garbage collected because they are not used anywhere. In no case does the static _instance field variable change its value more than once, the single time that it goes from null to a valid value. Hence consumers of this code will only ever see the same instance, despite the fact that multiple instances have been created.
Lock free programming
Joe Duffy, in his book entitled Concurrent Programming on Windows actually analyses this very pattern that you are trying to use on chapter 10, Memory models and Lock Freedom, page 526.
He refers to this pattern as a Lazy initialization of a relaxed reference:
public class LazyInitRelaxedRef<T> where T : class
{
private volatile T m_value;
private Func<T> m_factory;
public LazyInitRelaxedRef(Func<T> factory) { m_factory = factory; }
public T Value
{
get
{
if (m_value == null)
Interlocked.CompareExchange(ref m_value, m_factory(), null);
return m_value;
}
}
/// <summary>
/// An alternative version of the above Value accessor that disposes
/// of garbage if it loses the race to publish a new value. (Page 527.)
/// </summary>
public T ValueWithDisposalOfGarbage
{
get
{
if (m_value == null)
{
T obj = m_factory();
if (Interlocked.CompareExchange(ref m_value, obj, null) != null && obj is IDisposable)
((IDisposable)obj).Dispose();
}
return m_value;
}
}
}
As we can see, in the above sample methods are lock free at the price of creating throw-away objects. In any case the Value property will not change for consumers of such an API.
Balancing Trade-offs
Lock Freedom comes at a price and is a matter of choosing your trade-offs carefully. In this case the price of lock freedom is that you have to create instances of objects that you are not going to use. This may be an acceptable price to pay since you know that by being lock free, there is a lower risk of deadlocks and also thread contention.
In this particular instance however, the semantics of a singleton are in essence to Create a single instance of an object, so I would much rather opt for Lazy<T> as #Centro has quoted in his answer.
Nevertheless, it still begs the question, when should we use Interlocked.CompareExchange? I liked your example, it is quite thought provoking and many people are very quick to diss it as wrong when it is not horribly wrong as #Blindy quotes.
It all boils down to whether you have calculated the tradeoffs and decided:
How important is it that you produce one and only one instance?
How important is it to be lock free?
As long as you are aware of the trade-offs and make it a conscious decision to create new objects for the benefit of being lock free, then your example could also be an acceptable answer.
In order not to use 'double-checked locking mambo-jambo' or simply not to implement an own singleton reinventing the wheel, use a ready solution included into .NET 4.0 - Lazy<T>.
public class Singleton
{
private static Singleton _instance = new Singleton();
private Singleton() {}
public static Singleton Instance
{
get
{
return _instance;
}
}
}
I am not convinced you can completely trust that. Yes, Interlocked.CompareExchanger is atomic, but new Singleton() is in not going to be atomic in any non-trivial case. Since it would have to evaluated before exchanging values, this would not be a thread-safe implementation in general.
what about this?
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();
}
}
It's the fifth version on this page:
http://www.yoda.arachsys.com/csharp/singleton.html
I'm not sure, but the author seems to think its both thread-safe and lazy loading.
Your singleton initializer is behaving exactly as it should. See Raymond Chen's Lock-free algorithms: The singleton constructor:
This is a double-check lock, but without the locking. Instead of taking lock when doing the initial construction, we just let it be a free-for-all over who gets to create the object. If five threads all reach this code at the same time, sure, let's create five objects. After everybody creates what they think is the winning object, they called Interlocked­Compare­Exchange­Pointer­Release to attempt to update the global pointer.
This technique is suitable when it's okay to let multiple threads try to create the singleton (and have all the losers destroy their copy). If creating the singleton is expensive or has unwanted side-effects, then you don't want to use the free-for-all algorithm.
Each thread creates the object; as it thinks nobody has created it yet. But then during the InterlockedCompareExchange, only one thread will really be able to set the global singleton.
Bonus reading
One-Time Initialization helper functions save you from having to write all this code yourself. They deal with all the synchronization and memory barrier issues, and support both the one-person-gets-to-initialize and the free-for-all-initialization models.
A lazy initialization primitive for .NET provides a C# version of the same.
This is not thread-safe.
You would need a lock to hold the if() and the Interlocked.CompareExchange() together, and then you wouldn't need the CompareExchange anymore.
You still have the issue that you're quite possibly creating and throwing away instances of your singleton. When you execute Interlocked.CompareExchange(), the Singleton constructor will always be executed, regardless of whether the assignment will succeed. So you're no better off (or worse off, IMHO) than if you said:
if ( _instance == null )
{
lock(latch)
{
_instance = new Singleton() ;
}
}
Better performance vis-a-vis thread contention than if you swapped the position of the lock and the test for null, but at the risk of an extra instance being constructed.
An obvious singleton implementation for .NET?
Auto-Property initialization (C# 6.0) does not seem to cause the multiple instantiations of Singleton you are seeing.
public class Singleton
{
static public Singleton Instance { get; } = new Singleton();
private Singleton();
}
I think the simplest way after .NET 4.0 is using System.Lazy<T>:
public class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton() { }
}
Jon Skeet has a nice article here that covers a lot of ways of implementing singleton and the problems of each one.
Don't use locking. Use your language environment
Mostly simple Thread-safe implementation is:
public class Singleton
{
private static readonly Singleton _instance;
private Singleton() { }
static Singleton()
{
_instance = new Singleton();
}
public static Singleton Instance
{
get { return _instance; }
}
}

Refactoring a static class to use with dependency injection

We need to use an unmanaged library in our code that has static methods. I'd like to introduce the library operation as a dependency in my code. And apart from having static methods, the library has an initialization method and a settings method, both are global. So I can't just wrap this in an instance class, because if one instance changes a setting, all other instances will be affected, and if one instance gets initialized, all other instances will be reinitialized.
I thought about introducing it as a singleton class. This way it will be in an instance class, but there will only be one instance thus I won't have to worry about changing the settings or initialization. What do you think about this approach? I'm pretty new to the dependency injection pattern and I'm not sure if the singleton pattern is a good solution? What would your solution be to a similar case?
Edit: The initialization takes a parameter too, so I can't just lock the method calls and re-initialize and change settings every time it is called.
Edit 2: Here are the signatures of some methods:
public static void Initialize(int someParameter)
// Parameter can only be changed by re-initalization which
// will reset all the settings back to their default values.
public static float[] Method1(int someNumber, float[] someArray)
public static void ChangeSetting(string settingName, int settingValue)
If you only need to set the settings once at start up, then I would recommend making a non-static wrapper class which does all the initialization of the static class in its own static constructor. That way you can be assured that it will only happen once:
public class MyWrapper
{
public MyWrapper()
{
// Do any necessary instance initialization here
}
static MyWrapper()
{
UnManagedStaticClass.Initialize();
UnManagedStaticClass.Settings = ...;
}
public void Method1()
{
UnManagedStaticClass.Method1();
}
}
However, if you need to change the settings each time you call it, and you want to make your instances thread-safe, then I would recommend locking on a static object so that you don't accidentally overwrite the static settings while they're still in use by another thread:
public class MyWrapper
{
public MyWrapper()
{
// Do any necessary instance initialization here
}
static MyWrapper()
{
UnManagedStaticClass.Initialize();
}
static object lockRoot = new Object();
public void Method1()
{
lock (lockRoot)
{
UnManagedStaticClass.Settings = ...;
UnManagedStaticClass.Method1();
}
}
}
If you need to pass initialization parameters into your class's instance constructor, then you could do that too by having a static flag field:
public class MyWrapper
{
public MyWrapper(InitParameters p)
{
lock (lockRoot)
{
if (!initialized)
{
UnManagedStaticClass.Initialize(p);
initialized = true;
}
}
}
static bool initialized = false;
static object lockRoot = new Object();
public void Method1()
{
lock (lockRoot)
{
UnManagedStaticClass.Settings = ...;
UnManagedStaticClass.Method1();
}
}
}
If you also need to re-initialize each time, but you are concerned about performance because re-initializing is too slow, then the only other option (outside of the dreaded singleton) is to auto-detect if you need to re-initialize and only do it when necessary. At least then, the only time it will happen is when two threads are using two different instances at the same time. You could do it like this:
public class MyWrapper
{
public MyWrapper(InitParameters initParameters, Settings settings)
{
this.initParameters = initParameters;
this.settings = settings;
}
private InitParameters initParameters;
private Settings settings;
static MyWrapper currentOwnerInstance;
static object lockRoot = new Object();
private void InitializeIfNecessary()
{
if (currentOwnerInstance != this)
{
currentOwnerInstance = this;
UnManagedStaticClass.Initialize(initParameters);
UnManagedStaticClass.Settings = settings;
}
}
public void Method1()
{
lock (lockRoot)
{
InitializeIfNecessary();
UnManagedStaticClass.Method1();
}
}
}
I would use a stateless service class, and pass in state info for the static class with each method call. Without knowing any details of you class, I'll just show another example of this with a c# static class.
public static class LegacyCode
{
public static void Initialize(int p1, string p2)
{
//some static state
}
public static void ChangeSettings(bool p3, double p4)
{
//some static state
}
public static void DoSomething(string someOtherParam)
{
//execute based on some static state
}
}
public class LegacyCodeFacadeService
{
public void PerformLegacyCodeActivity(LegacyCodeState state, LegacyCodeParams legacyParams)
{
lock (_lockObject)
{
LegacyCode.Initialize(state.P1, state.P2);
LegacyCode.ChangeSettings(state.P3, state.P4);
LegacyCode.DoSomething(legacyParams.SomeOtherParam);
//do something to reset state, perhaps
}
}
}
You'll have to fill in the blanks a little bit, but hopefully you get the idea. The point is to set state on the static object for the minimum amount of time needed, and lock access to it that entire time, so no other callers can be affected by your global state change. You must create new instances of this class to use it, so it is fully injectable and testable (except the step of extracting an interface, which I skipped for brevity).
There are a lot of options in implementation here. For example, if you have to change LegacyCodeState a lot, but only to a small number of specific states, you could have overloads that do the work of managing those states.
EDIT
This is preferable to a singleton in a lot of ways, most importantly that you won't be able to accumulate and couple to global state: this turns global state in to non-global state if it is the only entry point to your static class. However, in case you do end up needing a singleton, you can make it easy to switch by encapsulating the constructor here.
public class LegacyCodeFacadeService
{
private LegacyCodeFacadeService() { }
public static LegacyCodeFacadeService GetInstance()
{
//now we can change lifestyle management strategies later, if needed
return new LegacyCodeFacadeService();
}
public void PerformLegacyCodeActivity(LegacyCodeState state, LegacyCodeParams legacyParams)
{
lock (_lockObject)
{
LegacyCode.Initialize(state.P1, state.P2);
LegacyCode.ChangeSettings(state.P3, state.P4);
LegacyCode.DoSomething(legacyParams.SomeOtherParam);
//do something to reset state, perhaps
}
}
}

Encapsulating an expensive resource without using a Singleton

I am working on updating a legacy application that is absolutely rife with Singleton classes. A perfect example would be the SnmpConnector class:
public SnmpConnector
{
public static IEnumerable<string> HostIpAddresses
{
...
}
private static SnmpConnector instance;
public static SnmpConnector Instance
{
if (instance == null)
instance = new SnmpConnector();
return instance;
}
private SnmpConnector()
{
foreach (string IpAddress in HostIpAddresses)
{
...
}
}
...
}
The goal of this update is to increase testability of the codebase, and as such I want to get rid of the Singletons. I've already abstracted away the data source of the SnmpConnector to either get data from a test database or from querying a live server:
public interface ISnmpDataSource
{
public DataTable MacTable
{
get;
private set;
}
public DataTable PortTable
{
get;
private set;
}
...
}
public TestSnmpDataSource : ISnmpDataSource
{
public FileInfo DataSource
{
get;
private set;
}
...
}
public SnmpDataSource : ISnmpDataSource
{
public List<string> HostIpAddresses
{
get;
private set;
}
...
}
public SnmpConnector
{
public SnmpConnector(ISnmpDataSource DataSource)
{
...
}
...
}
Now, I'm trying to test these components and running into the problem that probably caused SnmpConnector to be a Singleton in the first place: it takes an ungodly amount of time to test the SnmpDataSource. It turns out that fetching the MAC table and Port table from live switches takes somewhere between 10 and 20 seconds. I've already written 13 unit tests for this particular class, so it takes over two minutes for just these tests to complete. As annoying as this is, it gets worse once these updates get published to our original codebase. With this new refactoring, there is nothing stopping a programmer from creating and discarding an SnmpDataSource repeatedly.
Now, the data from these tables is largely static; the old Singleton and the new SnmpDataSource both maintain a cache that was only updated every four hours. Will I have to make SnmpDataSource a Singleton to prevent this problem?
Use dependency injection, and either pass the SnmpDataSource into anything that needs it, or potentially pass in a Func<SnmpDataSource> which can create the instance lazily as necessary.
Is your goal that the SnmpDataSource should update itself, or that callers will get a new version after a few hours?
You could try wrapping/decorating the SnmpDataSource with a cache-aware version that implements the same interface, then inject the cache-aware version.
*edit -- or you could do what Jon suggested where the factory Func does the caching instead (it will return a new instance or a cached version depending on when the last one was created). Same thing, slightly different implementation. Jon's version probably makes more sense.
public CachedSnmpDataSource : ISnmpDataSource
{
private DateTime m_lastRetrieved;
private TimeSpan m_cacheExpiryPeriod;
private List<string> m_hostIpAddresses;
private Func<SnmpDataSource> m_dataSourceCreator
public CachedSnmpDataSource(Func<SnmpDataSource> dataSourceCreator, TimeSpan cacheExpiryPeriod)
{
m_dataSourceCreator = dataSourceCreator;
m_cacheExpiryPeriod = cacheExpiryPeriod;
}
public List<string> HostIpAddresses
{
get
{
if(!IsRecentCachedVersionAvailable())
{
CreateCachedVersion();
}
return new List<string>(m_hostIpAddresses);
}
private bool IsRecentCachedVersionAvailable()
{
return m_hostIpAddresses != null &&
(DateTime.Now - m_lastRetrieved) < m_cacheExpiryPeriod;
}
private void CreateCachedVersion()
{
SnmpDataSource dataSource = m_dataSourceCreator();
m_hostIpAddresses = dataSource.HostIpAddresses;
m_lastRetrieved = DateTime.Now;
}
}
...
}
After a couple of iterations, I've ended up with a neat solution to this problem. I'm going to leave the accepted answer as is, but this is what I ultimately used:
ISnmpDataSource is responsible for fetching data, as before.
The SnmpConnector knows to only query if its own cache is invalid.
A static Factory class maintains a Dictionary<ISnmpDataSource, SnmpConnector>. There is a static BuildSnmpConnector(ISnmpDataSource) method based on this dictionary.
Using the library now looks like this:
IEnumerable<string> IpAddresses = ...;
string SqlConString = #"...";
ISnmpDataSource Switches = new SnmpDataSource(IpAddresses, SqlConStr);
SnmpConnector instance = Factory. BuildSnmpConnector(Switches);
I had a few problems with how I implemented GetHashCode and Equals for the ISnmpDataSource implementations, but formalizing a definition of equality pretty much fixed all those problems.
I'm pretty happy with the final result; the Factory class is responsible for limiting instantiation, while the SnmpConnector is responsible for caching query results, while the ISnmpDataSource is responsible for actually running queries. I'm sure there is a better organization out there, but this one is clean enough for use.

How to implement a singleton in C#?

How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project. I want to have them 'Global' and not need to manually bind them every object I create.
If you are just storing some global values and have some methods that don't need state, you don't need singleton. Just make the class and its properties/methods static.
public static class GlobalSomething
{
public static int NumberOfSomething { get; set; }
public static string MangleString( string someValue )
{
}
}
Singleton is most useful when you have a normal class with state, but you only want one of them. The links that others have provided should be useful in exploring the Singleton pattern.
Singletons only make sense if both of these conditions are true:
The object must be global
There must only ever exist a single instance of the object
Note that #2 does not mean that you'd like the object to only have a single instance - if thats the case, simply instantiate it only once - it means that there must (as in, it's dangerous for this not to be true) only ever be a single instance.
If you want global, just make a global instance of some (non signleton) object (or make it static or whatever).
If you want only one instance, again, static is your friend. Also, simply instantiate only one object.
Thats my opinion anyway.
Singleton != Global. You seem to be looking for the keyword static.
You can really simplify a singleton implementation, this is what I use:
internal FooService() { }
static FooService() { }
private static readonly FooService _instance = new FooService();
public static FooService Instance
{
get { return _instance; }
}
Hmm, this all seems a bit complex.
Why do you need a dependency injection framework to get a singleton? Using an IOC container is fine for some enterprise app (as long as it's not overused, of course), but, ah, the fella just wants to know about implementing the pattern.
Why not always eagerly instantiate, then provide a method that returns the static, most of the code written above then goes away. Follow the old C2 adage - DoTheSimplestThingThatCouldPossiblyWork...
I would recommend you read the article Exploring the Singleton Design Pattern available on MSDN. It details the features of the framework which make the pattern simple to implement.
As an aside, I'd check out the related reading on SO regarding Singletons.
Ignoring the issue of whether or not you should be using the Singleton pattern, which has been discussed elsewhere, I would implement a singleton like this:
/// <summary>
/// Thread-safe singleton implementation
/// </summary>
public sealed class MySingleton {
private static volatile MySingleton instance = null;
private static object syncRoot = new object();
/// <summary>
/// The instance of the singleton
/// safe for multithreading
/// </summary>
public static MySingleton Instance {
get {
// only create a new instance if one doesn't already exist.
if (instance == null) {
// use this lock to ensure that only one thread can access
// this block of code at once.
lock (syncRoot) {
if (instance == null) {
instance = new MySingleton();
}
}
}
// return instance where it was just created or already existed.
return instance;
}
}
/// <summary>
/// This constructor must be kept private
/// only access the singleton through the static Instance property
/// </summary>
private MySingleton() {
}
}
Static singleton is pretty much an anti pattern if you want a loosely coupled design. Avoid if possible, and unless this is a very simple system I would recommend having a look at one of the many dependency injection frameworks available, such as http://ninject.org/ or http://code.google.com/p/autofac/.
To register / consume a type configured as a singleton in autofac you would do something like the following:
var builder = new ContainerBuilder()
builder.Register(typeof(Dependency)).SingletonScoped()
builder.Register(c => new RequiresDependency(c.Resolve<Dependency>()))
var container = builder.Build();
var configured = container.Resolve<RequiresDependency>();
The accepted answer is a terrible solution by the way, at least check the chaps who actually implemented the pattern.
public class Globals
{
private string setting1;
private string setting2;
#region Singleton Pattern Implementation
private class SingletonCreator
{
internal static readonly Globals uniqueInstance = new Globals();
static SingletonCreator()
{
}
}
/// <summary>Private Constructor for Singleton Pattern Implementaion</summary>
/// <remarks>can be used for initializing member variables</remarks>
private Globals()
{
}
/// <summary>Returns a reference to the unique instance of Globals class</summary>
/// <remarks>used for getting a reference of Globals class</remarks>
public static Globals GetInstance
{
get { return SingletonCreator.uniqueInstance; }
}
#endregion
public string Setting1
{
get { return this.setting1; }
set { this.setting1 = value; }
}
public string Setting2
{
get { return this.setting2; }
set { this.setting2 = value; }
}
public static int Constant1
{
get { reutrn 100; }
}
public static int Constat2
{
get { return 200; }
}
public static DateTime SqlMinDate
{
get { return new DateTime(1900, 1, 1, 0, 0, 0); }
}
}
I like this pattern, although it doesn't prevent someone from creating a non-singleton instance. It can sometimes can be better to educate the developers in your team on using the right methodology vs. going to heroic lengths to prevent some knucklehead from using your code the wrong way...
public class GenericSingleton<T> where T : new()
{
private static T ms_StaticInstance = new T();
public T Build()
{
return ms_StaticInstance;
}
}
...
GenericSingleton<SimpleType> builder1 = new GenericSingleton<SimpleType>();
SimpleType simple = builder1.Build();
This will give you a single instance (instantiated the right way) and will effectively be lazy, because the static constructor doesn't get called until Build() is called.
What you are describing is merely static functions and constants, not a singleton. The singleton design pattern (which is very rarely needed) describes a class that is instantiated, but only once, automatically, when first used.
It combines lazy initialization with a check to prevent multiple instantiation. It's only really useful for classes that wrap some concept that is physically singular, such as a wrapper around a hardware device.
Static constants and functions are just that: code that doesn't need an instance at all.
Ask yourself this: "Will this class break if there is more than one instance of it?" If the answer is no, you don't need a singleton.
hmmm... Few constants with related functions... would that not better be achieved through enums ? I know you can create a custom enum in Java with methods and all, the same should be attainable in C#, if not directly supported then can be done with simple class singleton with private constructor.
If your constants are semantically related you should considered enums (or equivalent concept) you will gain all advantages of the const static variables + you will be able to use to your advantage the type checking of the compiler.
My 2 cent
Personally I would go for a dependency injection framework, like Unity, all of them are able to configure singleton items in the container and would improve coupling by moving from a class dependency to interface dependency.
You can make a simple manual static singleton implementation for your common (non-static) class by adding a static property Instance (name can vary) into it with initialization like this:
public class MyClass
{
private static MyClass _instance;
public static MyClass Instance => _instance ?? (_instance = new MyClass());
// add here whatever constructor and other logic you like or need.
}
Then it can be resolved anywhere from this namespace like this:
var myClass = MyClass.Instance; // without any new keyword
myClass.SomeNonStaticMethod();
// or:
MyClass.Instance.SomeNonStaticMethod();
// or:
MyClass.Instance.SomeNonStaticProperty = "new value";
By hiding public constructor, adding a private static field to hold this only instance, and adding a static factory method (with lazy initializer) to return that single instance
public class MySingleton
{
private static MySingleton sngltn;
private static object locker;
private MySingleton() {} // Hides parameterless ctor, inhibits use of new()
public static MySingleton GetMySingleton()
{
lock(locker)
return sngltn?? new MySingleton();
}
}
I have written a class for my project using Singleton pattern. It is very easy to use. Hope it will work for you. Please find the code following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TEClaim.Models
{
public class LogedinUserDetails
{
public string UserID { get; set; }
public string UserRole { get; set; }
public string UserSupervisor { get; set; }
public LogedinUserDetails()
{
}
public static LogedinUserDetails Singleton()
{
LogedinUserDetails oSingleton;
if (null == System.Web.HttpContext.Current.Session["LogedinUserDetails"])
{
oSingleton = new LogedinUserDetails();
System.Web.HttpContext.Current.Session["LogedinUserDetails"] = oSingleton;
}
else
{
oSingleton = (LogedinUserDetails)System.Web.HttpContext.Current.Session["LogedinUserDetails"];
}
//Return the single instance of this class that was stored in the session
return oSingleton;
}
}
}
Now you can set variable value for the above code in your application like this..
[HttpPost]
public ActionResult Login(FormCollection collection)
{
LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
User_Details.UserID = "12";
User_Details.UserRole = "SuperAdmin";
User_Details.UserSupervisor = "815978";
return RedirectToAction("Dashboard", "Home");
}
And you can retrieve those value like this..
public ActionResult Dashboard()
{
LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
ViewData["UserID"] = User_Details.UserID;
ViewData["UserRole"] = User_Details.UserRole;
ViewData["UserSupervisor"] = User_Details.UserSupervisor;
return View();
}
In c# it could be (Thread safe as well as lazy initialization):
public sealed class MySingleton
{
static volatile Lazy<MySingleton> _instance = new Lazy<MySingleton>(() => new MySingleton(), true);
public static MySingleton Instance => _instance.Value;
private MySingleton() { }
}

Categories