1

I am trying to write a generic method which goes a particular DB table depending on the entity which is passed (all valid entities implement IStaticData) :

IEnumerable<T> GetEnumerable<T>() where T : IStaticData

I am using the nop commerce framework and have at my disposal IRepository<T> for every entity in the database e.g. IRepository<User>

I cannot think of a better way to write this than "switching" on the entity type passed and using the relevant Repository class - is there a better way!?

5
  • That's typically what we do too, unless your data layer is abstracted to the point that you are creating separate databaseService objects for each individual object type. Although if I remember correctly, you can't switch using typeof in .Net, and have to use a sequence of if statements instead.
    – Rachel
    Commented Mar 16, 2016 at 17:36
  • IDictionary<Type, IRepository<T>> Commented Mar 17, 2016 at 0:24
  • Difficult to answer without context. Perhaps an extension method on IRepository<T> would be a better choice. Commented Mar 17, 2016 at 13:43
  • @Rachel, it's very ugly i agree, switching on primitive types only means a heap of "if" statements
    – Ben Toomer
    Commented Mar 17, 2016 at 13:55
  • I did decide in the end however to change my approach and consolidate all the tables since the data was just KeyValuePair<TKey, TValue>. This makes my life much simpler for the future
    – Ben Toomer
    Commented Mar 17, 2016 at 13:59

1 Answer 1

3

You could use an abstract factory, like this:

public interface IRepository<T> { }

public interface IRepositoryFactory
{
    IRepository<T> GetRepository<T>();
}

That just leaves the question, what is the implementation of IRepositoryFactory?

I was going to describe Castle Windsor's typed factory facility but I Googled and nopCommerce uses another dependency injection container, Autofac.

I haven't used Autofac (next on my list) but these containers all do essentially the same thing. Here's a stackoverflow post describing creating an abstract factory with Autofac. The question looks exactly like your scenario, and the first answer shows a factory using Autofac.

If you haven't already used it, sorry, that was a really clumsy pointer toward dependency injection. But this is exactly the sort of problem it addresses. You're trying to figure out a way to create the right class for the right interface without if/thens or switches. DI handles that and more.

I went to Autofac's home page and the code samples right there give a really concise picture of what it does. Look at just the top two. On the left it shows how you tell it what classes to use for which interfaces. You can name them one at a time or even scan an assembly for classes that implement an interface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.