Domanda

I am working on an application for which I need to write a data access layer. My first thought was to create a bunch of repositories for each entity that I need but I am now facing the a challenge with separating the different actions of a repository. I would like to hear your thoughts on this.

First, I would like to support two types of communication to the database - direct sql queries (for example, insert into, update, etc) and bulk inserts like loading data from a file (or other source). However, both of these implementation do different things:

  • The simple repository fires a query to SQL server
  • The bulk repository first adds a record to a file or in memory. Once it is done processing all records, it synchronizes with the database.

My first attempt at the class structure for this is:

  public class Product{

  }

  public interface IProductRepository {
    Product GetProduct(int id);
    void CreateProduct(Product p);
  }

  public class SqlProductRepository : IProductRepository
  {
    public Product GetProduct(int id)
    {
      throw new NotImplementedException();
    }

    public void CreateProduct(Product p)
    {
      throw new NotImplementedException();
    }   
  }

  public class BulkLoadRepository : IProductRepository
  {
    public Product GetProduct(int id)
    {
      throw new NotImplementedException();
    }

    public void CreateProduct(Product p)
    {
      throw new NotImplementedException();
    }    
  }

However, this structure is missing a synchronization function at the end for the bulk repository. If I do end up adding a Sync() function, I will need to leave it empty for the "simple" repository.

Any thoughts on how to support both functionalities but still hide them behind one interface?

Thanks in advance!

È stato utile?

Soluzione

First of all, why are you creating an interface for each object type. A repository would usually just have Get, Create, Update, Delete methods for example, maybe a generic Get... where the IRepository is also generic.

You could have a second interface inheriting IRepository which has the Sync method and only the Bulk repository implements that one. In this case you can still access both repositoriesmethods defined byIProductRepository`

Or have a base class for Bulk repositories which implements/defines sync.

Altri suggerimenti

I'm not sure why you would leave it empty for the simple repository. Sync == Commit in most of my repositories. Although more precisely this is the UnitOfWork pattern, not the repository pattern.

Exposing a separate commit method is very common for transactional systems.

Repository and Unit of Work patterns - How to save changes

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top