// class implements IModelFactory -> IFactoryModel CreateInstance(string modelName)
private Dictionary<string, Type> _availableTypes;
public ModelFactory() {
LoadTypes();
}
public IFactoryModel CreateInstance(string modelName)
{
Type t = GetTypeToCreate(modelName);
//NOTE: handle null here
return Activator.CreateInstance(t) as IFactoryModel;
}
private void LoadTypes()
{
_availableTypes = new Dictionary<string, Type>();
Type[] assemblyTypes = Assembly.GetExecutingAssembly().GetTypes();
assemblyTypes.Where(x => x.GetInterface(typeof(IFactoryModel).ToString()) != null).ToList()
.ForEach(y => _availableTypes.add(y.Name.ToLower(), y));
}
private IFactoryModel GetTypeToCreate(string name)
{
_availableTypes.TryGetValue(name, out Type t);
return t ?? null;
}
source:
https://app.pluralsight.com/library/courses/patterns-library/table-of-contents