Reputation: 436
As I have learned about Application Service layer, it must be stateless i.e. it shouldn't store any dynamic data in properties or fields. So different instances of Application Service would do almost the same thing. So does it mean we may implement it as a static class or using singleton pattern?
Upvotes: 1
Views: 500
Reputation: 14070
Statelesness is a somewhat loaded concept that people use to mean different things in a service.
At a minimum, it shouldn't remember anything about a request between two invocations.
By an extended definition, it should minimize the amount of state information it manages.
Whatever the case, neither static nor singleton are necessary or sufficient to make a stateless service. A static service can perfectly be stateful, as can a singleton one.
In other words, all properties of statelessness can hold true even if you use a non-static, non-singleton class. Which should probably be should be your default mode, unless you have very good other reasons to use these approaches.
Upvotes: 1
Reputation: 15569
I am quoting from this pluralsight course by Julie Lerman & Steve Smith.
Domain services should be stateless, though they may have side effects. What this means is we should always be able to simply create a new instance of a service to perform an operation, rather than having to rely on any previous history that might've occurred within a particular service instance. But of course, the result of calling a method on a service might result in changes to the state of the system itself.
Same concept applies to Application Services. Note that Stateless does NOT mean static
. As an example, we can have an EmailSenderService
... the service sends an email and potentially returns Success/Failure. Later if we want to send another email, we instantiate a new EmailSenderService
to send the email... we do not rely on the fact that the previous email was sent successfully or not.
Also as Eben has pointed out, services are often injected in the consumers, static
types cannot be injected and that's one good reason for not using static
services.
This is a really good article by Jimmy Bogard about services in DDD.
I also recommend checking this project by Dino Esposito, as a sample DDD project.
Upvotes: 2
Reputation: 13256
A stateless service should have all the state passed in when calling the relevant method. The application service itself may have other dependencies that would be injected.
Dependency inversion is your friend here and I would not recommend a static
class. Rather use some dependency injection with a singleton pattern and if you are so inclined I'd suggest using a dependency injection container such as Castle Windsor, StructureMap, Autofac, Ninject, Unity, or SimpleInjector --- I'm sure there are others.
If you do run into singletons that require state I have a short video on that.
Upvotes: 2