lundi 22 mai 2017

Utilizing a Generic Repository Interface

I've seen various uses of the repository pattern. I'm leaning toward a pattern that I see far less frequently, and I'm wondering if there is a good reason for that.

Pattern 1: Access the Repo through the business object by injecting into the Constructor

        Class Teacher : IPerson
        {
            Private IRepository myRepository;

            Internal Teacher(IRepostory repo){
                This.myRepository = repo;
            }

            Public overrides void Save(){
                Repo.Save(this);
            }
        }

example:

 IPerson p = DataAccess.GetPersonFromId(id);
 p.Name = "Bill";
 p.Save();

Benefits

  1. The constructor will be internal and access only by a factory pattern, so I'm not worried about the complexity here.
  2. IPerson forces an implementation of Save() method but teacher does not need to know how it's being persisted
  3. Works similar to an Entity Framework Proxy object
  4. I can call Save() on an Iperson object without needing to know its an invoice
  5. Application -> Business Object -> Repository seems like the logical dependency structure.

Cons

  1. The business objects are not Plain Old C# objects anymore.

  2. Any changes to the entity repository are likely going to need to change the "Person" interface.

  3. Should I be applying the same pattern with an IFactory? Do we keep injecting services?

Pattern 2: Access Directly

        IPerson p = DataAccess.GetPersonFromId(id);
        IRepostory repo = DataAccess.GetRepositority()
        p.Name = "Bill";
        repo.Save(p);

Benefits

  1. Seems like the simpler way to do things.

Cons

  1. I can't very well make use of a generic repository that can be used for all derived types. I would like to use an Irepository interface that can take a Person Type and know how to persist it.

Summary

I was leaning toward pattern 1, but almost every example I see out there uses a version of Pattern 2.

The main goal is that I don't want to be using TeacherRepository anywhere in the Application Layer. I would like to rely entirely on IRepository. However, It doesn't look like I can do that in Pattern 2, because Save() needs to know its dealing with a Teacher to properly persist the data.

Are there any unique other patterns that could allow me to work with a generic repository?

Aucun commentaire:

Enregistrer un commentaire