-
Notifications
You must be signed in to change notification settings - Fork 11
Services
With the use of the IMorestachioFormatterService
you can inject services into your formatters or make objects available via the $services
variable.
To prepare an object to be used as a service, you have to add it to the Services
property of the IMorestachioFormatterService
via the ParserOptionsBuilder.New().WithService(service)
extension method or one of overloads.
You can ether add the service instance directly or use the factory methods. There are some build in services available provided by the framework such as:
- ParserOptions - The
ParserOptions
object that is used to render the template - ScopeData - The current
ScopeData
, containing execution options - ILogger - When set the logger supplied by the
ParserOptions
object
Note: all objects listed above are only available for formatters not via the $service variable!.
To get a service within a formatter you simply add an parameter to your function, matching the type and annotated with the ExternalDataAttribute
.
Example ToString formatter
[MorestachioFormatter("ToString", "Formats a value according to the structure set by the argument")]
public static string Formattable(IFormattable source, string argument, [ExternalData]ParserOptions options)
{
return source.ToString(argument, options.CultureInfo);
}
this example shows the build-in ToString formatter. It is injected with the ParserOptions.
Another use-case is the consumption of a service directly within your template. To access any explicitly added service, you can access the $services
variable directly in your template and handle it the same as an object where all properties are named like the type the service has.
The example uses the optional Build-In FileSystemService
.
Example $service with FileSystemService
var template = @"{{$services.FileSystem.File.Create(FileName)}}";
var options = await ParserOptionsBuilder.New()
.WithTemplate(template)
.WithFileSystem(() => new FileSystemService(tempDirectory))
.BuildAndParseAsync();
When adapting an existing IServiceContainer with morestachio via the ParserOptionsBuilder.WithServiceContainer(IServiceContainer)
extension method, the services within that container are only available for Formatters as well. This is because for a Template based lookup there has to be an name relation with all services as it is only possible to write a string in the template and the .net IServiceCollection does not have such relation.