6

Can Services in a domain-driven design be implemented as C# static class? What are the drawbacks of this choice? Can it be implemented as a non-singleton non-static class?

9

As far as I can see, making a service class static does not affect its DDD'ness.

There are however other issues with static classes, primarily testability. It becomes difficult to unit test the class, and even more difficult to test classes that have dependencies to your static class.

Therefore I would always create the class as an instance class, and define an interface for it. This allows me to replace the class by test doubles when testing other classes that have a dependency to this class.

But it doesn't make it more DDD, it just makes it more TDD :)

2

In my opinion it makes total sense to use static classes for domain services furthermore because this type of services must be stateless.

Regarding the testability of static classes, I tend to use TDD for this kind of classes with zero mocks. If I'm confident that this class is working well, I have no problem that the classes that depends on it use it as it is, with no mocking required.

Martin Fowler wrote an article where it describes this kind of approach by calling it "Sociable Tests"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.