Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Singleton != Global. You seem to be looking for the keyword static.

Singletons only make sense if both of these conditions are true:

  1. The object must be global
  2. 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.

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 aboiut 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.

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() { }
}
public class Singleton
{
   private static Singleton _instance;
   public static Singleton Instance => _instance ?? (_instance = new Singleton());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top