Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Repository Factory Class

Tags:

c#

repository

public enum RepositoryType
{
    ClinicRepository,
    MedicationRepository,
    PatientRepository,
    TreatmentRepository
}

public class ObjectFactory<T>
{
    public static IRepository<T> GetRepositoryInstance(RepositoryType type)
    {
        switch (type)
        {
            case RepositoryType.ClinicRepository:
                return new what ?;

            default:
                return what ?
        }
    }
}

public interface IRepository<T>
{
    void Add(T item);
    void Remove(int id);
    void Update(T item);
    IList<T> GetAll();
    T GetItemById(int id);
}

I'm trying to create a RepositoryFactory class and I copied what I've done so far. Could anyone please help me to figure this out ? I'm stuck ! Thanks in advance

edit :

I want something like this at the end. Is it possible to make 1 Repository class and implement something like

dc.THATOBJECT.insertonsubmit(item) ?

public class TreatmentRepository : IRepository<Treatment>
{
    public void Add(Treatment item)
    {
        using (PatientsDataContext dc = new PatientsDataContext())
        {
            dc.Treatments.InsertOnSubmit(item);
            dc.SubmitChanges();
        }
    }
like image 324
Kubi Avatar asked Jan 12 '11 14:01

Kubi


1 Answers

The simplest of factories just requires that your types derived from IRepository have parameterless constructors.

public class ObjectFactory {
    public static TRepository GetRepositoryInstance<T, TRepository>() 
      where TRepository : IRepository<T>, new() {
        return new TRepository();
    }
}

If you require specific constructors for a given repository type, you can specify the objects as an object array and create them using CreateInstance

public class ObjectFactory {
    public static TRepository GetRepositoryInstance<T, TRepository>(
      params object[] args) 
      where TRepository : IRepository<T> {
        return (TRepository)Activator.CreateInstance(typeof(TRepository), args);
    }
}

To use either of these, you just need to say

var treatmentRepo = 
    ObjectFactory.GetRepositoryInstance<Treatment, TreatmentRepository>();
like image 117
Mark H Avatar answered Oct 06 '22 01:10

Mark H