Schema and editors
Every application built with Optionary gets one JSON Schema for its configuration, merged from the declarations of every
assembly it references. Editors use it to complete section and key names in appsettings.json, YAML and TOML files, to show
the documentation you wrote on the options types, and to flag unknown keys and out-of-range values.
Fragments
Section titled “Fragments”The generator embeds one fragment per section in the assembly:
[assembly: AssemblyMetadata("Optionary.Schema.v1:<section path>", "<JSON Schema of the section's value>")]Each fragment is a Draft-07 schema of the section’s value, with every object type described once under definitions.
Every key also has a case-insensitive patternProperties twin with the same schema, so retries: 99 is checked even when
written as Retries.
Hand-written fragments in the same format are supported: a library whose section isn’t described by an options type can
add the attribute itself, and it is merged like any other. Only the Optionary.Schema.v1: prefix is read.
Contributing a fragment from a package or another generator
Section titled “Contributing a fragment from a package or another generator”A package that configures a section of its own, such as an HTTP-client generator that reads HttpClients:Petstore, can
declare that section’s schema to the projects that use it. Source generators can’t see each other’s output, so there are
three ways in.
The OptionarySchemaFragment item. Include is the section path, and exactly one metadata holds the schema of the
section’s value, in the fragment format above: Schema (inline JSON) or File (a JSON file):
<ItemGroup> <OptionarySchemaFragment Include="HttpClients:Petstore" File="$(MSBuildThisFileDirectory)petstore.schema.json" /> <OptionarySchemaFragment Include="@(OpenApiClient->'Clients:%(ClientName)')" Schema='{"type":"object","properties":{"BaseAddress":{"type":"string","format":"uri"}}}' /></ItemGroup>Put it in a project file, or in a package’s buildTransitive/<PackageId>.targets to declare the section in every project
that references the package. As the second item shows, it can be a transform of the package’s own items, one section each.
Optionary checks each item and turns it into the
[assembly: AssemblyMetadata("Optionary.Schema.v1:HttpClients:Petstore", "...")] attribute, compacted to one line, before
the assembly info is generated. From there it is a fragment like a generated one: it goes into the library schema and its
package, and every host that references the project merges it. Several fragments for one section, from items and from
options types, are merged into one.
- The schema is a JSON object, with any object types it reuses under
definitionsand every local$refpointing at one of them. Leave outpatternPropertiesandpropertyNamesif you like: the fragment is permissive, and the host’s merge closes the section to the keys you list. Fileis relative to the project; a package’s targets should use$(MSBuildThisFileDirectory). Editing the file rebuilds the project and updates the schemas.Schemais an MSBuild metadata value, so MSBuild expands property and metadata references ($(...),%(...)) in it and unescapes%XX. Write%25for a%followed by two hex digits. Single-quote the attribute, as above, so the JSON’s double quotes need no escaping, and write'for a'.;,$,@and%on their own are kept.- The project has to reference
Optionary: its targets read the item. In a package, that means depending onOptionary. - With
GenerateAssemblyInfoorGenerateAssemblyMetadataAttributesset tofalse, Optionary writes the attribute to$(IntermediateOutputPath)<project>.OptionarySchemaFragments.csinstead.OptionarySchema=falseignores the items. - Setting neither or both of
SchemaandFile, an invalid section path, a missing file and a schema that isn’t a fragment are build errors,OPT1002toOPT1005.
Emit the attribute from your generator. A generator can add the AssemblyMetadata attribute to its own output: the
merge reads the compiled assembly, not the source, so it doesn’t matter which generator wrote it. The schema has to be in the
fragment format, as a C# string literal.
Declare an options type. When the section binds to a class that the consuming project can already see (one in your package’s runtime assembly), a package can add a source file declaring it, and Optionary’s generator then binds the section and describes it:
<ItemGroup> <Compile Include="$(MSBuildThisFileDirectory)PetstoreConfiguration.cs" Visible="false" /></ItemGroup>[assembly: Optionary.Optionary<Petstore.PetstoreClientOptions>("HttpClients:Petstore")]This doesn’t work for a class your generator writes: Optionary’s generator doesn’t see it.
Annotations that reach the schema
Section titled “Annotations that reach the schema”| Source | Schema |
|---|---|
[Description], else the XML <summary> |
description. For a record parameter, its <param>. |
[Range], length attributes |
minimum/maximum, minLength/maxLength, item counts |
[RegularExpression] |
pattern, when the expression can be anchored |
[Url], [EmailAddress] |
format |
[Obsolete] |
deprecated and a deprecation message |
| A constant initializer or parameter default | default, except an empty string |
- Ranges and defaults are also written into the description, since editors don’t show them.
- The XML summary is read from source whether or not
GenerateDocumentationFileis on.<inheritdoc />and<include>produce no description. - Annotations JSON Schema can’t express are dropped with
OPT0008. - Fragments are permissive: nothing is
requiredunlessOptionarySchemaRequiredistrue, which marksrequiredmembers,[Required]properties and value-type constructor parameters without defaults.
The library schema
Section titled “The library schema”Every project that isn’t a host (a library) writes its own fragments to $(IntermediateOutputPath)ConfigurationSchema.json
and packs it at the NuGet package root. This library schema is permissive and rooted at the configuration root, the
layout Aspire’s packages use, so Visual Studio and other tools that understand it can read it. A library that targets
several frameworks writes one per framework and packs the first one’s. A library with no sections writes nothing.
The application schema
Section titled “The application schema”A host is a test project (IsTestProject) or an application (OutputType Exe or WinExe, or an Android
application). Set OptionarySchemaHost to true or false to override the detection; a host framework can set it from its
own application detection.
A host merges its own fragments and those of every referenced assembly into
$(BaseIntermediateOutputPath)appsettings.schema.json, normally obj/appsettings.schema.json.
- Stable path. Editors can point at it and the setting can be checked in. A host that targets several frameworks
writes it from its first target framework, and
$(IntermediateOutputPath)appsettings.schema.json(for exampleobj/Debug/net10.0/) from the others. - Copied and published. It is copied to
$(OutDir)next toappsettings.jsonand published asappsettings.schema.json. A project that references the host (a test project referencing an application) doesn’t get a second copy. SetOptionarySchemaCopyToOutputtofalseto keep it inobj/only, for hosts that embed their configuration (MAUI, Uno). - No collisions. A hand-made
appsettings.schema.json(Web SDK content, or one from a reference) is removed from the publish items so it doesn’t collide with the generated one (NETSDK1152). - Strict. Each Optionary section, and the object types it uses, accepts only its own keys. The check is a
case-insensitive
propertyNamespattern rather thanadditionalProperties: false, somessageis accepted andMesageis flagged, with an error that lists the known keys. The root, parents shared between sections, dictionaries and sections declared by more than one assembly stay open.OptionarySchemaStrict=falseturns the check off. - Includes SchemaStore. SchemaStore’s
appsettings.jsonschema is embedded, not referenced, soLogging,KestrelandConnectionStringscomplete too, online or offline. The copy ships with Optionary (Apache-2.0).OptionarySchemaIncludeSchemaStore=falseleaves it out. - Deterministic. Section paths compare ignoring case. When fragments spell a section or key differently, the ordinal-smallest spelling is shown. A section several assemblies declare is merged into one object. The same fragments always give a byte-identical file, whatever order the references come in.
The build target runs after CoreCompile, skips design-time builds and writes only when its inputs change. Merging runs
in a compiled MSBuild task that reads fragments with System.Reflection.Metadata: no assembly is loaded, and nothing is
embedded in your application. All the properties are in the MSBuild reference.
Visual Studio
Section titled “Visual Studio”Visual Studio’s JSON editor reads schemas from JsonSchemaSegment items. Optionary adds them with the file pattern
appsettings\..*json, the one Aspire’s packages use:
- a segment for the host’s
obj/appsettings.schema.json; - a segment for each referenced package that ships a
ConfigurationSchema.jsonat its root, as libraries built with Optionary do. A package that declares its own segment for the file (Aspire’s client packages do) is skipped, so completions aren’t doubled. Project references need none: their fragments are in the host’s file.
Nothing needs configuring. The items are added after ResolveAssemblyReferences, so they exist in the design-time builds
Visual Studio runs when it loads the project. OptionarySchemaVisualStudio=false turns the segments off and keeps the
schema files. If completion doesn’t appear after the first build, close and reopen the file.
Visual Studio Code
Section titled “Visual Studio Code”VS Code needs one mapping per file type: its JSON support reads json.schemas, and the YAML (Red Hat) and Even Better
TOML extensions read yaml.schemas and evenBetterToml.schema.associations. Put them in .vscode/settings.json:
{ "json.schemas": [ { "fileMatch": ["/MyApp/appsettings*.json"], "url": "./MyApp/obj/appsettings.schema.json", }, ], "yaml.schemas": { "./MyApp/obj/appsettings.schema.json": ["MyApp/appsettings*.yaml", "MyApp/appsettings*.yml"], }, "evenBetterToml.schema.associations": { "^.+/MyApp/appsettings.*\\.toml$": "./MyApp/obj/appsettings.schema.json", },}- JSON reports unknown keys, completes the canonical names and shows descriptions on hover.
- YAML does the same. Its
fileMatchglobs don’t match files under a dot-folder. - TOML needs the explicit association: Even Better TOML can’t use the SchemaStore catalog, and it reports an unknown
key on the table header rather than on the key. It ignores
deprecated.
Let Optionary write the settings
Section titled “Let Optionary write the settings”Set OptionaryScaffoldEditorSettings in the application’s project file:
<PropertyGroup> <OptionaryScaffoldEditorSettings>true</OptionaryScaffoldEditorSettings></PropertyGroup>On build, Optionary creates or updates only its own entries in .vscode/settings.json (json.schemas, yaml.schemas
and evenBetterToml.schema.associations), pointing at the host’s obj/appsettings.schema.json.
- Comments, trailing commas, indentation, line endings and a byte-order mark are preserved. Other settings and other entries are untouched, and when the mappings are already there the file isn’t rewritten.
- Each host gets entries of its own, keyed by its schema path, so several applications can share one file. An entry that already maps the host’s schema only gets what is missing. If you move a project, delete its old entries by hand.
- The file goes in the nearest ancestor of the project that contains a
.gitentry, or the project folder when there is none.OptionaryEditorSettingsDirectorypicks another folder (relative to the project); it must contain the project, because VS Code resolves the schema path relative to the folder it opened. - Only hosts write it, once per build (from the first target framework), never in design-time builds, and not when
OptionarySchemaisfalse. - A file Optionary can’t update safely (not valid JSON with comments, not UTF-8, an unexpected shape, read-only) is left alone, and the build warns with the entries to paste.
- Optionary never adds
$schemakeys or# yaml-language-servermodelines to your configuration files.
It is off by default because it edits a file that is probably checked in. Existing mappings keep working across Optionary versions, since entries are matched by schema path.
JetBrains Rider
Section titled “JetBrains Rider”Rider uses its own JSON Schema mappings:
- Open Settings | Languages & Frameworks | Schemas and DTDs | JSON Schema Mappings.
- Add a mapping, choose
obj/appsettings.schema.jsonas the schema file, set the version to Draft 7, and add the application’sappsettings*.jsonfiles. - Rider applies JSON Schema mappings to YAML files too; add the
appsettings*.yamlfiles the same way.
Other editors
Section titled “Other editors”- yaml-language-server reads a
yaml.schemassetting like VS Code’s, or a# yaml-language-server: $schema=...modeline in the file. - Taplo takes the schema from
.taplo.toml.
When completion doesn’t work
Section titled “When completion doesn’t work”- No completion at all. Build the project: the file is written after compilation. Check that the mapping’s path is
relative to the folder the editor opened, and that the file name matches
appsettings*. - A key is flagged as unknown. Check its spelling against the options type. Set
OptionarySchemaStricttofalseto stop the check. - A section is missing. The application schema only covers assemblies the host references. Check the options type is
declared and the declaration wasn’t rejected (look for
OPTdiagnostics). - Quoted numbers are flagged. Write the number without quotes.