2

Let's say we have an application layer with some command handler and we use an Entity Framework database context/ORM context in that handler.

I would invert dependencies from the Entity Framework/ORM to the Application layer like this:
Create a repository interface with some CRUD functions in the application layer component and then in an ORM component make an implementation which gets the datacontext injected.

Why should I need a repository pattern for this instead? When do I need this pattern at all?

1

The sentence, "Create a repository interface with some CRUD functions in the application layer component and then in an ORM component make an implementation which gets the datacontext injected" is a reasonably good description of the repository pattern.

As such, it's unclear what you are asking with "Why should I need a repository pattern for this instead?" It is the repository pattern. What you don't necessarily need is a 3rd party implementation of that pattern.

1

There is nothing about the repository pattern and dependency injection that is mutually exclusive.

The primary purpose of the Repository Pattern (example) is to divorce your application logic from having to know anything about how to access the data. Whether the Repository uses ORM, an Object Database directly, or just stores files on disk, are simply implementation details of the Repository itself.

The Repository Pattern is used in a few architectural patterns like:

  • DDD
  • Onion Architecture
  • And similar

The Repository Pattern also allows you to architect Command/Query separation so that how you look up data does not have to match how you store data. It's not uncommon for your data needs to grow, while still supporting your application logic. For example:

  • Your project starts with only a traditional RDBMS (SQL database)
  • You add a search layer to optimize faceted search (Elastic Search or Apache SOLR)
  • You add caching to improve response times
  • You add a graph database to perform friends of friends searches

All of these concerns are implementation details for how to store and retrieve data. You shouldn't have to recode the rest of your application to support all of these approaches.

Do I Need the Repository Pattern?

That really depends on your project. If you are simply doing a research project for school, or a one-off tool to do a specific job, then probably not.

If you need the flexibility to improve your data access story over time without breaking your application, it's a good tool.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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