How to choose a class whose method to call

Oct 27 2020 1:48 AM
Hi all,
 
I would appreciate a hand in designing my code. So far I haven't found a way to do this.
 
I have a number of classes for different entities (currently 7 but there can be more in the future). I need a method in each of these classes that authorizes user's access to a file resource. Implementation varies but an exception must be thrown if user does not have access to the file in question.
 
Problem is, when a file is being accessed, I need to call the authorization method of the correct class based on the data on the file. Files are stored in a db table and one of the fields in that table determines which entity the file is related to and how to find which user has access to the file.
 
So I must read the file data from db, then see which entity it's related to and then call the authorization method of the correct class.
 
Is there a way in C# to accomplish this without having to make a switch case structure on the file field value?
 
Example of the classes used:
  1. public class FileAttachment    
  2. {    
  3.     // other FileAttachment class stuff     
  4.         
  5.     protected void AuthorizeFileAccess(FileAttachmentData file)    
  6.     {    
  7.         // file has a field which tells which entity it relates to    
  8.         // here I need to choose which class to use based on the file data    
  9.     }    
  10. }    
  11.     
  12.     
  13. // simplified example of a related entity    
  14. public class ChatMessage    
  15. {    
  16.     public int SenderUserId;    
  17.     public int RecipientUserId;    
  18.         
  19.     // here I need a method that checks that chat message sender's or recipient's    
  20.     // user id matches the user id of the logged in user    
  21.     // if not, throw exception    
  22. }    
  23.    
  24. And this is what I want to avoid:  
  25. switch (file.SourceValue)    
  26. {    
  27.     case "ChatMessageAttachmentFile":    
  28.         var cm = new ChatMessage();    
  29.         cm.AuthorizeAttachmentAccess();    
  30.     case "OtherAttachmentFile":    
  31.         var other = new SomeOtherClass();    
  32.         other.AuthorizeAttachmentAccess();    
  33.     default:    
  34.         throw new Exception("Access denied");    
  35. }

Answers (2)