c# - Is this a good way to check if only one instance of a class exists without resorting to using the Singleton pattern? -


i have class in program of want 1 copy. don't want use singleton pattern though couple of reasons (* see below). know i'll have 1 copy of class because i'll 1 calling constructor.

in class's constructor, want check 1 copy of class exist , throw exception if more 1 exists. code below pattern use case?

public class mysingletonalternative : idisposable {     private static int _count = 0;      public mysingletonalternative()     {         int newvalue = system.threading.interlocked.increment(ref _count);         if (newvalue > 1)         {             throw new notimplementedexception();         }     }      public void dispose()     {         int newvalue = system.threading.interlocked.decrement(ref _count);         if (newvalue < 0)         {             throw new objectdisposedexception("mysingletonalternative");         }     } } 

* why don't want use singleton:

  1. i want able control when class created. in traditional c# singleton pattern, construction happens non-deterministically.

  2. i want avoid global variables.

  3. when i'm debugging code , exception raised in singleton's private constructor, visual studio highlights exception, highlights wrong line of code, in different file.

  4. i don't want create object lazily (using lazy<t>). 1 instance of class exist life of application. gain nothing constructing lazily.

use ioc container unitycontainer. erase of points you've mentioned why don't want use singleton (in means of global variables or static). able controll creation of lifetime-instance , inject classes need use this.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -