Search code examples
c#interfacegenerated-code

How to create a collection of singletons from all classes in a namespace


Lets say we have a namespace called AllFoos.

And Lets say all classes in the AllFoos namespace implement a specific interface called IFoo and are all singletons.

Now we have:

HashSet<IFoo> myFoos = new HashSet<IFoo>();

What would be the code to populate the collection MyFoos with the singleton instances of all the classes in AllFoos?

The singleton implementation for all of these classes is:

private static IFoo _instance = new ConcreteImplementationOfFoo1();

public static IFoo Instance
{
     get
     {
          return _instance;
     }
}

Solution

  • If you would use a dependency injection framework you could:

    1. register your classes as "singleton" in the container
    2. register all implementations easily (good frameworks allow mass-registration based on some patterns)
    3. resolve all implementations of your interface as a list

    If you want to go the classic way, you have to tell how your singleton pattern looks like (e.g. static Instance property?), and it can be solved with classic reflection as mentioned in the comments already.