You can instantiate an object of a generic type with parameters using reflection.
public T GetContext()
{
Uri myUri = new Uri(ApiSettings.ODataUrl);
Type contextType = typeof(T);
DataServiceContext context = (T)Activator.CreateInstance(contextType, myUri);
// Do whatever
return context;
}
The second argument of Activator.CreateInstance
is an array of type object
, so you can pass in whatever number or type of arguments the constructor requires. To make the above code work, all of the T
types you use have to have a constructor with the same signature, like this:
public class MyContext1 : DataServiceContext
{
public MyContext1(Uri uri)
{
// Do whatever
}
}
public class MyContext2 : DataServiceContext
{
public MyContext2(Uri uri)
{
// Do whatever
}
}
You're not limited to a single parameter either - this works for constructors with any number of parameters. Just make sure that you're using the same number and type of arguments for each class that you instantiate this way.