Create a service
Updated
A service is a class of business functions any script can call. Public methods
become the contract I<Name>. You resolve it with GetService<I<Name>>().
Note
If the same logic is about to appear in a second handler, it is already a service. Events, commands, and posting scripts stay thin: check, call the service, return. Copy-paste between handlers is the signal to extract.
How to#
Three files in Services/<Name>/:
<Name>.json—kind: "Service",scriptMetaIdof the code.<Name>Service.script.json—scriptType: "Service".<Name>Service.cs— the class name equals the service name, not the script name. That name is what becomesI<Name>:
public partial class LocationService
{
private readonly IDataService _data;
public LocationService(IDataService data) => _data = data;
public async Task<Guid?> FindCountryByCityAsync(Guid cityId)
{
var city = await _data.GetByIdAsync("City", cityId);
return city?["Country"] as Guid?;
}
}
Platform services arrive through the constructor. From an event or command,
call context.GetService<ILocationService>(); from any other partial,
GetService<ILocationService>().
Several implementations of one IFoo are Chain of Command:
the top layer starts, next<T>(…) goes down. Swallowing the rest is
[Replace]. A different behaviour that is not a wrap needs a different
contract name.
Warning
A service must not build register movements. Compute the number (amount, tax, rate). The posting script writes
transactions.Add(new <Register> { … }). Same-looking movements in two documents are normal, not duplication.
Magic numbers and mode codes belong in global constants
(GlobalConstants.<Group>.<Name>), not in the service —
Add a global constant.
A resource key bound to the service's script is not found when the service runs — the running script is the caller. Put the key on the event or command that shows the text. See script resources.
Bump modelVersion in the same change.
What's not there yet#
A service is not an HTTP endpoint. A public URL is a
data entity (/odata/…) or a
web service (/api/rest/…).