question

TAIIELMEHDI-2849 avatar image
0 Votes"
TAIIELMEHDI-2849 asked Bruce-SqlWork answered

Use Multiple Type in Generic T C#

i have this interface base repo with genric type T

 public interface IRepositoryBase<T> where T : class
 {
     void Add(T obj);
 }

and this interfaces heritance from the IRepositoryBase

 public interface IClass1Repository : IRepositoryBase<Class1>
 {
 }
 public interface IClass2Repository : IRepositoryBase<Class2>
     {
     }

and this the class implementation of IRepositoryBase

 public class RepositoryBase<T> : IRepositoryBase<T> where T : class
 {
     private readonly Context _context;
     public RepositoryBase(Context context)
     {
         _context = context;
     }
     public void Add(T obj)
     {
         _context.Set<T>().Add(obj);
     }

}
and this the implementaion of class1 & class2

 public class class1Repository : RepositoryBase<Students>, IClasse1Repository
     {
         public class1Repository (Context context) : base(context)
         {
         }
     }

 public class class2Repository : RepositoryBase<Students>, IClasse2Repository
     {
         public class2Repository (Context context) : base(context)
         {
         }
     }

& in this methode i need to return one of Repo

 private IRepositoryBase<> GetRepository(sting a)
         {
             var scope = _serviceScopeFactory.CreateScope();
             switch (tableName)
             {
    
                 case "class1":
                     return scope.ServiceProvider.GetService<IClass1Repository>();
                 case "class2":
                     return  scope.ServiceProvider.GetService<IClass2Repository>();
             }
             return null;
         }

But inside the bracket in IRepositoryBase he take one type class1 or class2 so in my case I need to return by params a.

how can i do to use union or something else to set the multiple type in barcket and choose the return by conditon in params a







dotnet-csharpdotnet-aspnet-core-webapi
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Bruce-SqlWork avatar image
0 Votes"
Bruce-SqlWork answered

As the interfaces do not have a common base, you use type object

 private object GetRepository(string a)

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.