tags:

views:

62

answers:

2

This seems like basic problem, but I'm struggling with it (maybe because of tiredness).

E.g. - if i create instance of repository like this =>

var repositoryType = typeof(Repository<>).MakeGenericType(entityType);
// repository type==object :(
var repository = ServiceLocator.Current.GetInstance(repositoryType); 

What's the best way to call repository.All() method? Is reflection the only way?

+1  A: 

In .Net 3.5, it is not possible to do this without reflection or worse.

SLaks
What would be worse? :D
Arnis L.
Building a method at runtime using System.Linq.Expressions would be worse.
SLaks
The only real competition to Expression is ILGenerator... for me Expression wins every time ;-p
Marc Gravell
Ouch... Now my head aches. Seems that it's time for a break.
Arnis L.
+2  A: 

It depends whether Repository<> exposes some non-generic interface (like ITable compared to Table<T> in LINQ-to-SQL). If not, you have to use reflection. If it does, then cast to the non-generic interface:

IRepository repository = (IRepository)ServiceLocator
    .Current.GetInstance(repositoryType); 
IList data = repository.All();

In 4.0, you could also consider dynamic:

dynamic repository = ServiceLocator.Current.GetInstance(repositoryType); 
IList data = repository.All();
Marc Gravell
Created `NonGenericRepository` that takes entityType as an argument in constructor. Seems awkward but better than reflection.
Arnis L.
I'd have gone with an interface myself, but whatever works. And indeed, reflection and generics are not good friends.
Marc Gravell
Wondering - if type covariance in .Net 4.0 could solve this (I haven't checked it thoroughly yet)?
Arnis L.
Not unless you a: have an interface, b: can define it as strictly "in" or "out", c: have a common reference-type ancestor, etc. In short: I don't think it is a likely option.
Marc Gravell