Concepts: Services (Core)
This section will discuss services, how they work, and what they are within the Sodacore framework.
Introduction
A service, is a thing, a thing that does stuff. Yeah I know, not very descriptive, but in essence, a service is a class with init
, start
, and stop
lifecycle hooks that the framework will call at the appropriate times.
Services, at least what I have used them for (and had in mind) were to provide a way to manage long-running processes, for example, a HTTP server, a Discord bot, etc. These are all things that you want to start when your application starts, and stop when your application stops.
Can I use services for other things?
Absolutely, you could, you could create a service that simply dispatches an event every minute. Why you would want to do that, I don't know, but you could. The idea of a service is that it's anything. I treat them personally as something that has lifecycle events that need to be managed, and usually that might trigger events. You see, the core part of the Sodacore framework is the services, the HTTP service, the WebSocket service, the Discord service, etc... They all run instances of something that then, using meta-programming (decorators), will find controllers that match the "service" and dispatch events to them, that is the core of the framework, and you can see that if you look at any of the services within the monorepo.
So yes, you can use them for anything, and yes, they support dependency injection, so you can inject providers, other services, etc.
Creating a service
Same as the providers, super simple.
import { Service, BaseService } from '@sodacore/di';
@Service()
export class MyService extends BaseService {
public async init() {
// Called when the framework is initialising
this.logger.info('MyService is initialising');
}
public async start() {
// Called when the framework is starting
this.logger.info('MyService is starting');
}
public async stop() {
// Called when the framework is stopping
this.logger.info('MyService is stopping');
}
}
That's it, as noted before, the autowire will pick it up, register it, and call the lifecycle hooks at the appropriate times.
Note: The
BaseService
has thelogger
property injected already and has some empty function definitions, so you can just override what you need.
Using a service
I mean... as I said above, services are things that run, so you don't really "use" them, but you can inject them into other classes if you need to access something within them.