C # template for abstract class code

I have an abstract "Action" class that has the types ActionAppointment, ActionCall, ActionEmail and ActionLetter. I am trying to write a function that will be DRY at our service level, so we no longer write CRUD requests.

I have some update logic in our service layer (many other codes have been removed for brevity):

private IServiceResponse UpdateAction<T>(T action, string originalActionStatus) where T : Action { if (action.GetType() == typeof(Action)) { _actionRepository.Update(action); } else if (action.GetType() == typeof(ActionAppointment)) { _actionAppointmentRepository.Update(action as ActionAppointment); } else if (action.GetType() == typeof(ActionCall)) { _actionCallRepository.Update(action as ActionCall); } else if (action.GetType() == typeof(ActionEmail)) { _actionEmailRepository.Update(action as ActionEmail); } else if (action.GetType() == typeof(ActionLetter)) { _actionLetterRepository.Update(action as ActionLetter); } } 

Unfortunately, as our repositories are configured, I have to use specially named repositories (i.e. I cannot update the ActionLetter via _actionRepository, even if it is obtained from Action)

I read different templates and it looks like something similar to the Factory template, but I don’t see how to make it work.

Am I missing something stupid?

+6
source share
2 answers

Can't you just write an overload of this method for each type of action? Forget about the <T> and typeof things - what you do is implement the built-in language function (method overload) manually and in a fragile way.

+11
source

Let here the inverse logic:

 abstract class Action { protected abstract Repository GetRepository(); protected void Update(){ this.GetRepository().Update(this); } } 

All you have to do is override GetRepository in each of the classes. For instance:

 class ActionAppointment : Action { protected override Repository GetRepository() { return _actionAppointmentRepository; } } 
-2
source

Source: https://habr.com/ru/post/891244/


All Articles