Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# singleton pattern in a static class?

My event dispatcher class loosely couples instances of other classes by implementing sort of signals-slots design pattern.

Only one unique event dispatcher is supposed to exist in an application. Since my Dispatcher class – which does all the work – inherits from Dictionary<TKey, TValue>, it cannot be declared static.

To overcome this constraint, I implemented a main static wrapper class EVD with a private property evd which provides the Dispatcher singleton, along with the public static methods Subscribe, UnSubscribe, and Dispatch, which wrap the singleton's corresponding methods:

namespace EventDispatcher
{
    public static class EVD
    {
        static Dispatcher evd { get { return Singleton<Dispatcher>.Instance; } }

        public static void Subscribe(string name, EvtHandler handler)
        {
            evd.Subscribe(name, handler);
        }
        public static void UnSubscribe(string name, EvtHandler handler = null)
        {
            evd.UnSubscribe(name, handler);
        }
        public static void Dispatch(string name, object sender, EvtArgs e = null)
        {
            evd.Dispatch(name, sender, e);
        }
    }

    class Dispatcher : Dictionary<string, Event> { /* main event dispatcher */ }

    static class Singleton<T> where T : /* generic singleton creation */
}

So here is my question:

Does it really make sense to create a singleton instance in a static class? AFAIK a static class is unique anyway. So maybe it would be best practice not to create the singleton and declare the evd property just like so:

static Dispatcher evd = new Dispatcher();

What about lazy intantiation and thread safety in that case? At least the generic singleton class uses Lazy<T> and is said to be thread safe.

Or should I better declare the property like so:

static Dispatcher _evd;
static Dispatcher evd 
{ 
    get { return _evd ?? (_evd = new Dispatcher()); }
}

I'm afraid I don't completely understand all that lazy instatantiation and thread safety stuff...

Thanks for any help, Don P

like image 231
Don P Avatar asked Sep 28 '22 02:09

Don P


1 Answers

No, since you can't create instances of a static class there will only be one copy of the field, so there is no need to use the Singleton pattern.

Place the construction in the static constructor, which is guaranteed to be called only once, and is thereby automatically thread-safe: https://msdn.microsoft.com/en-us/library/k9x6w0hc.aspx

Extra reference: it look corresponding to the "static field" inside "Employee Type Object" here: http://www.rvenables.com/linkjackandsufferaccidentaldroptable/clr_via_csharp_f4.9.png

like image 94
Mattias Avatar answered Oct 18 '22 18:10

Mattias