Search code examples
c#factory-pattern

Forcing the use of a factory object to instantiate a class


I have the special case where an object needs to be a singleton on a per thread basis. So I'd like to use a static factory method of a Factory class to instantiate those instances. To ensure that the factory class is used (since it caches per thread) the constructor needs to be protected.

So let's say I have a class like this.

public class XXXX : Model {
    protected XXXX() {
    }
}

I would like to use a factory class like this.

public class Factory {

     private static Dictionary<int,Model> _singletons;

     public static T Instance() where T : Model {
          int thread = Thread.CurrentThread.ManagedThreadId;
          if(!_singletons.ContainsKey(thread))
          {
              _singletons[thread] = new T();
          }
          return (T)_singletons[thread];
     }
}

Then later I can get a reference to each singleton like this, and the reference will be unique for each thread.

XXXX m = Factory.Instance<XXXX>();

How can I do this so that the Factory class has access to create instances. One issue is that classes will be defined in other DLLs that will be loaded at run-time. All I can know is that they are derived from Model and have protected/private constructors.


Solution

  • Some options:

    • reflection
    • register delegate that creates the class with factory class
    • configure your DI container to behave the way you need for that type of classes

    Approximate code for delegate approach:

    public class Factory {
       private static Dictionary<Type, Func<Model>> creators;
       public void AddCreator<T>(Func<T> creator) where T:Model
       {
          creators.Add(typeof(T), ()=> creator());
       }
    
       public static T Instance() where T : Model 
       {
           return (T)(creators[typeof(T)] ());
       }
    }