Search code examples
c#design-patternsdomain-driven-designdomainservices

can I use generic services in domain service with different business or not?


I have problem in create generic domain service or not?? I have "BaseEntity" that inherit any entity from it and has been every moment set value when update or insert method called in repository .my domain service layer that implements every entity business. my problem is what I have to do when I have one business that implement in every Services in domain service.can I use generic class and interface to manage BaseEntity and then change business for example for Update method override base update method or I used for every entity one service class with one interface with separate business???


Solution

  • For the most part I would advise against any generic base classes for your domain. If you have a hierarchy of classes it may be that you have a more technical/framework domain but even there you should favour composition over inheritance.

    I would not, for instance, use a BaseEntity as I find it superfluous. The closes you could come is perhaps something like an IRepository<T> with a T Get(Guid id) and a void Save(T instance) method but you would have to think exactly where you would use something like this. You could make your roles explicit by following the single responsibility principle and go with IRepositoryGet and IRepositorySave. However, these type of interfaces are only useful where you have some broad commonality between the objects and that typically doesn't happen. You may find that some lookup data seems to fit into this space but even there you may rather want to design a common repository as opposed to individual repositories for each type.

    What you most definitely want to avoid is to have a coarse-grained interface and then have various NotImplementedExceptions thrown. When you find that you are doing that rather split the interfaces into more fine-grained versions and implement only the desired interfaces. In this way you can use safe casting to ensure that the interface is implemented before making a call to the method.