lundi 26 avril 2021

How to dynamically choose Repository object

I have this structure:

class BaseCategory {}

class Category1 : BaseCategory {}
class Category2 : BaseCategory {}
class Category3 : BaseCategory {}
.....
class Category50 : BaseCategory {}

Clients call the API passing catType like category1, category2,... and the API does the following(Repository in if/else statements):

List<Category> categories;
if(catType == "category1")
  categories = Repository<Category1>.GetAll();
else if(catType == "category2")
  categories = Repository<Category2>.GetAll();
else if(catType == "category3")
  categories = Repository<Category3>.GetAll();
else if(catType == "category4")
  categories = Repository<Category4>.GetAll();
return categories;

one of approaches could be using dynamic type which makes the first call very slow and I'll lose strong typing.

My other approach is using a dictionary with key: cateType and value: RepositoryTypeX. And I don't want to use reflection.

I wonder is there any better way to achieve this.

Aucun commentaire:

Enregistrer un commentaire