My database is relatively small, 8 tables, each with less than 5 columns. I use EF. I created single repository class, but now that I think it might not be the right way to use it. Should I have separate repository class for each of my controllers? Lets say I have Products, Users, Unicorns would it be fine to have a single repository class to operate with all of those and instantiate in each of those controllers, or should I create a separate repository class for each of those?
One of the pivotal concepts of DDD is the aggregate root - this is the 'top level' entity through which you manage entire sets of related entities.
For example, in a retail scenario the 'Order' would be an aggregate root through which you could access the Order itself, a list of OrderItems (ie Product + Amount + modifiers such as discounts), BillingAddress, ShippingAddress and PaymentMethod. Each of those is closely related to the order itself, to the point where they have no reason to exist outside the scope of the order.
Each aggregate root should have a repository which owns the responsibility of persisting the entire subgraph of objects under the root. So in the above example, you would NOT want or need a repository for OrderItems which allows access to order items independently; instead you should implement a single OrdersRepository which deals with Orders and all their sub-components as a single unit.
Depending on your specific domain model you may need one or more repositories, but certainly not one per entity type. The key question to ask when looking for aggregate roots is "does this entity have its own identity and lifecycle?" Orders do, OrderItems don't.
Think Domain-Driven Design, and with that in mind, you divide the logical structure of your project not as classes only, but as domains also, which means all operations have got to do with the Product
are located within the ProductsController
and consequently within the ProductsRepository
, so I prefer many repositories each equipped with operations to deal with some aspect of your project.
Not all aspects may need a repository, but that is what you decide.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With