Repository Pattern Mixing With and Without Transactions

Viewed 16

I am refactoring my codebase to be less tightly coupled between services and data access/persistence by using the repository pattern. Today my service layer makes direct SQL calls to the database. I'm aiming to wrap my entities into separate Repositories (sometimes multiple tables can be access by a single repository) and support transactions.

Where I'm getting hung up is how to organize my code. Top level questions like should my services be instantiated objects or static classes/stateless modules. But on to my real reason for posting here - transactions. In some of my service an operation may open a transaction over some tables but during that transaction also read data in a non-transactional way from other tables. E.g. read and update from order and products table, but in between the read and update also read the customer details. This doesn't seem to fit well with how I've seen others use the repository model, where they dependency inject the repository model instantiation into the service object.

Going into the details, assuming I use services as objects (not static classes/modules), when using Repositories should I:

a) instantiate all the repositories my service may use (even if I don't end up using them) when creating the service through dependency injection, keeping them as private members in the service object, which my service logic can access

OR

b) create repositories within my service business logic when needed

I am leaning towards b, because I am thinking when I create my Repositories I will dependency inject my database connection/context* which will either be a transaction or a non-transaction database connection object. My service, which creates the database context(es), decides whether to use a transaction or non-transaction context. In the case of a transaction, the service would also be responsible for committing the transaction too.

I don't know if (b) is using the pattern wrong, and I don't know how else I'm meant to be able to decide whether to use transactions or not after creating the service.

Note I'm using TypeScript + Express (not C#).

Thanks

*I am using Knex query builder configured for postgres.

0 Answers
Related