Search code examples
c#.netdomain-driven-designrepository-patternpoco

Can POCO / Domain objects have dependencies injected to it


This is my current code structure for the business layer -

  • UserManager (service class) works on User (domain object)
  • CompanyManager (service class) works on Company (domain object)

Now, both my domain objects depend on

  • IUnitOfWork - (uses IUserRepository, ICompanyRepository)

I have read articles where it says domain objects should not have any dependencies on repositories. So my question is in two parts -

  1. Whether domain objects shouldn't have any dependencies? In the above case, what if some operation on 'Company' should trigger some operation on 'User', then can the Company object have a dependency on UserManager?
  2. If the domain object shouldn't have dependencies, then where should I keep those logic? Where should I call the save method on repository, or a call to UserManager when something happens on 'Company'?

Thanks!


Solution

  • In DDD, the domain layer will be inner most layer that encapsulates all the domain logic. It is recommended not to have any dependencies in your domain classes.

    In your scenario, it is ideal to use Domain Events

    1. Company domain should raise an event, e.g. "OnPolicyChanged", and this event should be listened at the UserManager and manager should invoke the domain logic in the User domain.

    2. It is not ideal to include the persistence logic in your domain layer. It should be at a higher level, e.g. A service/Infrastructure layer which should commit the changes to the database.