Search code examples
dependency-injectiondependenciesdomain-driven-design

Dependency between Application Layer and Domain Layer


I want to reduce the connection between ApplicationLayer and DomainLayer. Consider that I had created an AggregateRoot in Domain Project. It's Ok if I reference Domain directly from Application.
But I want to use the interfaces not the implementation, So I created Domain.Contract that keep the interfaces and contracts of Domain project!Domain has a refrence to this project to implements the interfaces. How can I use this contract in the application layer. in other words:

Domain has the reference of Domain.Contract.
Application Has the reference of Domain.Contract.

In Domain project I have Card Class
In Domain.Contract Project I have ICard interface In Application Project I want just reference to the Domain.contract and I have CommandHandlers method that create Card

CommandHandlerMethod()
{
   var card = ICard?!!! //What should I do here?
   repository.Save(card);
}

One approach that I found is to use a Factory. But factory should now the interface and implemented class, that they are in different project. If I use factory in Domain.contract project it will cause a loop in references. If I use Factory in Domain project how application project will use it?!


Solution

  • As I understood, you can define IFactory interface in 'Domain.Contracts' and leave its implementation in 'Domain'. Now Application layer would know only about 'Domain.Contracts' and the IFactory would be injected in 'ApplicationService' object. In fact the 'Factory' would not be a static class' Your code should be like this :

    public class AppService
    {
        public IFactory Factory { get; set; }
        public AppService(IFactory factory)
        {
           Factory = factory;
        }
        public void Handle(CreateCommand cmd)
        {
            var card = Factory.Create(cmd.Prop1);
            repo.Add(card);
        }
    }