Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Invoke Member of Generic Type

Status
Not open for further replies.

pa182

Programmer
Sep 4, 2010
1
GB
Hi, my application has the following interfaces:

public IDataContext {
IRepository<T> Repository<T>() where T : class;
}

public interface IRepository<T> where T : class {
T GetById(int id);
}

I have my own implementation setup and initialized using an ioc container. Usually i'd be able to say

var context = ServiceLocator.Current.GetInstance<IDataContext>();
context.Repository<Role>().GetById(1);

Which works fine but i have a case where i don't know the generic type until runtime. Ideally i'd like to be able to say:

Type myType = typeof(Role); // This is just shown as an example
var context = ServiceLocator.Current.GetInstance<IDataContext>();
context.Repository<myType>().GetById(1);

However this does not work. I'd imagine i'd have to use reflection to solve this unless i'm missing something obvious. I'd really appreciate it if someone could help. Thanks
 
correct, if you don't know the type until runtime, you cannot use generics. in that case you would need to do someting like
Code:
object o = context.Repostory(mytype).Get(id);
or
Code:
object o = context.Repostory.Get(id, mytype);
a third option is to create a supertype for example
Code:
abstract class User
{
}
class SuperUser : User
{
}
class NormalUser : User

var u = context.Repostory<User>.Get(id);
and the context/mappings would know whether to resolve a super or normal user.
[code]

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top