基于DDD架构的依赖注入标准疑问:各层注入主体咨询
Hey Leo, great questions—these are exactly the kinds of decisions that keep DDD implementations clean and maintainable. Let’s break this down layer by layer, sticking to core DDD principles:
1. Application Layer: Should ClientAppService Inject UserApplicationService or UserService?
Go with injecting UserApplicationService (the application-layer service) first—here’s why:
- Single Responsibility:
UserApplicationServiceshould own all user-related application use cases (like fetching user details, validating user status for business workflows).ClientAppServicecan focus solely on client-specific logic, reusing user-related workflows via the application service instead of mixing concerns. - Layered Encapsulation: The application layer’s job is to coordinate use cases, not dive into domain-layer details.
UserApplicationServicealready handles calls toUserService(domain layer), repositories, and external services.ClientAppServicedoesn’t need to know about those underlying dependencies, which keeps coupling low. - Exception: If you only need a tiny, pure domain logic snippet from
UserService(like validating a user ID format) and there’s no existing application-layer wrapper for it, you could injectUserServicedirectly. But try to avoid this long-term—wrap that logic in aUserApplicationServicemethod to keep your application layer consistent.
2. Domain Layer: Should ClientService Inject UserService?
Absolutely—if the dependency serves domain logic. Domain services exist to handle cross-aggregate or complex business rules that don’t fit neatly into a single entity. For example:
- If creating a client requires verifying that the associated user is in an active state (a domain rule),
ClientServiceshould injectUserServiceto handle that validation. - If a client’s permissions are derived from the linked user’s role (another domain rule),
ClientServiceneedsUserServiceto access that user-specific domain logic. - Just make sure this dependency is strictly for domain rules, not application-level tasks (like sending notifications or handling HTTP requests)—those belong in the application layer.
内容的提问来源于stack exchange,提问作者LeoFelipe
相关产品推荐
相关产品推荐

