Capiono
Capiono

Reputation: 220

How to reset a singleton instance in c#?

Is there are way to force a singleton instance to reset whenever a user update the database?

public class Example{
      private Dictionary<int, string> _list;

      private Example(){
        _list = new Dictionary<int, string>();
        //Get data from database here and add the data to _list
      }

      private class Nested{ 
          static Nested(){}
          internal static readonly Example Instance = new Example();
      }

      public static Dictionary<int, string> GetExample(){
         return Nested.Instance._list
      }

}

So, I do I reset _list when database is updated?

Thanks!

Upvotes: 2

Views: 10698

Answers (2)

RQDQ
RQDQ

Reputation: 15569

One way to do this is to use lazy loading and provide an "Invalidate" or "Reset" method.

public class Example
{
  private static Dictionary<int, string> _list;

  public static void Invalidate()
  {
       _list = null;
  }

  public static Dictionary<int, string> GetExample()
  {
      if (_list == null)
          _list = new Dictionary<int, string>();

     return _list;
  }
}

One thing to watch out for is this isn't set up for multithreaded at all. The Dictionary class isn't recommended for re entrant code and there needs to be some sort of locking in place in the GetExample and Invalidate methods.

Upvotes: 0

jonnii
jonnii

Reputation: 28312

The short answer is: No.

The closest thing you can get is to reset the dictionary:

public void Reset(){ _list.Clear(); }

Now the long answer...

Why are you using a singleton? I'm assuming it's because you read the GoF design pattern book and thought it looked like a fun idea. The singleton pattern breaks every tenet of object oriented design. You can't inherit from them, you break encapsulation and there's no chance of polymorphism.

In the example you've posted you're handing the inner workings of your class (the dictionary) to anyone who wants it. What if they change it? How will this work with threads?

If you only want one instance of your class in your application then only call new once, or use a dependency injection container with a singleton life style, but that's another topic altogether.

Urgh, I hate singletons.

Upvotes: 7

Related Questions