Use Multiple Type in Generic T C#

TAII EL MEHDI 21 Reputation points
2022-06-22T19:36:58.513+00:00

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

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,184 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,271 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,686 Reputation points
    2022-06-23T01:54:26.537+00:00

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

    private object GetRepository(string a)  
    
    0 comments No comments