Search code examples
c#architecturedomain-driven-designuser-rolesrepository-design

Where should I put query logic related to filtering data by role user in DDD architecture


I am following DDD architecture for my app. I have App layer, domain layer and data access layer(repository). Let say I would have 3 roles in my app: admin, supervisor, agency. Every role should access data that assigned to itself. So the problem is, should i put query logic in order to filter data by role in Repository like

var query = dataContext.Order.Where(...);
if(userRole = "admin")
query =.... filter by admin
If(usrRole = "supervisor")
query =.... 
return query.ToList();

I think the logic related to business logic and should put in domain layer. But I havent clear this one. Can you guys clear this out for me?


Solution

  • The best explanation I've read so far is the one from Patterns, Principles And Practices Of Domain-driven Design, published by Wrox. The image below resembles the core idea.

    onion arch

    All dependencies point inward, so the domain model depends on nothing else, and knows about nothing else. Therein it's pure, and can focus on what matters, the language of the domain.

    The application layer (containing the application services) exposes an API of use cases and orchestrates the requests with the involved domain services. Therefore, the code in application services is procedural, while the code in the domain model is usually much richer. That is, if the domain is complex enough to warrant it.

    But I digress, to answer your question, the application layer exposes interfaces for the infrastructure to implement (eg repository pattern). It's also the application layer that knows how to query the data (through the use of this interface), and filter it based on the role.

    The domain model should only receive the filtered collection, and focus only on one thing, processing the data.

    For completeness, DDD allows many architectures, as long as the domain has no dependencies. Though I find it easiest to grasp, thinking about it this way.