views:

79

answers:

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?

Thanks in advance.

+1  A: 
rama-jka toti
Something went haywire with your code formatting.
DanM
Edited original post to fix code. Sometimes it's hard to translate from specific situational code in an IDE to Markdown.
AJ
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.
rama-jka toti
Edited to fix code formatting.
JacobM
@Majkera, Much better now, thanks :)
DanM