jeudi 5 décembre 2019

Generic or specific repository when you need to support multiple ORM or sources?

I need to manipulate some data from a database via two different ways, Entity Framework and web service.

To simplify, lets say there are only two tables called A and B.

I am stuck on the design of this. Should I simply have two classes that derive from an interface that exposes the functions I want like so:

public interface IRepository
{
        bool AddA(A a);     
        bool RemoveA(A a);
        IEnumerable<A> GetAllA();
        bool AddB(B b);     
        bool RemoveB(B b);
        IEnumerable<B> GetAllB();
}

public class EfRepository : IRepository
{
        //actual code here
}

public class ServiceRepository : IRepository
{
        //actual code here
}

or should I try an approach which is more generic in nature:

public interface IRepository<T>
{
        bool Add(T t);
        bool Remove(T t);
        IEnumerable<T> GetAll();
        bool Update(T t);

}

public class EfARepository: IRepository<A>
{
        //actual code here

}

public class EfBRepository : IRepository<B>
{
        //actual code here
}

public class ServiceARepository: IRepository<A>
{
        //actual code here

}

public class ServiceBRepository : IRepository<B>
{
        //actual code here
}

The second approach seems cumbersome and repetitive since I am not really following the generic repository pattern because I'm not sure if its doable or worth the effort since Entity Framework already acts like a repository. Or would something like this be more sensible:

public class ARepository<Ef> : IRepository<A>
{
        //omitted
}
//or this
public class EfRepository<A> : IRepository<A>
{
        //omitted
}

But then again I can't wrap my head on injecting the context (Ef or service) into the classes and a repository of EF or vice versa doesn't really make much sense.

Please enlighten me and comment on the aforementioned designs and suggest a better approach or design for this scenario. Some examples in relation to this would be great!

Aucun commentaire:

Enregistrer un commentaire