1

I have a data access library that has a few classes that all implement the same interface, which has a generic type parameter:

public interface IGetByCommonStringRepository<TEntity> { TEntity GetByCommonStringColumn(string commonString); } public class Repository1<Entity1> : IGetByCommonStringRepository<Entity1> { public Entity1 GetByCommonStringColumn(string commonString) { //do stuff to get the entity } } public class Repository2<Entity2> : IGetByCommonStringRepository<Entity2> //...and so on 

Rather than forcing consumers of this library to instantiate one of the four repository classes separately for each <TEntity>, I am hoping that there's some way that I can create a static method in a "helper/utility" class in the same assembly that will be able to discern which implementation to instantiate, create an instance, and execute the GetByCommonStringColumn method. Something like...

public static TEntity GetEntityByCommonStringColumn(string commonString) where TEntity : class { IGetByCommonStringRepository<TEntity> repository = DoMagicalReflectionToFindClassImplementingIGetByCommonString(typeof(TEntity)); //I know that there would have to an Activator.CreateInstance() //or something here as well. return repository.GetByCommonStringColumn(commonString) as TEntity; } 

Is anything like this possible?

1
  • 1
    The classes in your example code don't implement IGetByCommonStringRepository<>. Commented Nov 5, 2009 at 18:04

1 Answer 1

1

That example still needs further fixing.. For each repository it is missing a constraint. For each public (right now it is invalid private) method it is also missing a functional body.. For that interface method it requires a generic argument.

Then try, or play around, if I understood you right:

public static TEntity clr_bloat_reflected_msdn_method<TEntity>(string commonString) where TEntity : class { Assembly a = Assembly.GetExecutingAssembly(); foreach (Type t in a.GetTypes()) if (!t.IsAbstract && typeof(IGetByCommonStringRepository<TEntity>).IsAssignableFrom(t)) return ((IGetByCommonStringRepository<TEntity>)Activator.CreateInstance(t)).GetByCommonStringColumn(commonString); return null; } 

Sign up to request clarification or add additional context in comments.

2 Comments

Edited original post to fix code. Sometimes it's hard to translate from specific situational code in an IDE to Markdown.
First it was interrupts, then my keyboard went, then Windows started the usual 7 day running hang and losing icons, audio etc, then it went into spelling. Now it's my code-formatting on stackoverflow.com @ ASP.NET MVC. Time to go and do serious work and lose yet another addiction.. sigh.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.