Template Class

Represents a text template with embedded code blocks that can be dynamically compiled and executed.

public class Template : IDisposable

Remarks

Building a template compiles it into an assembly that is loaded in a dedicated collectible AssemblyLoadContext. Dispose the template to unload that assembly as soon as the template is no longer needed; otherwise it is unloaded once the template becomes unreachable and the garbage collector runs.

Example

using var template = new Template();
template.Load("Hello <%=Name%>!");
template.Arguments.Add(new TemplateArgument("Name", typeof(string)));
var result = template.Run("Meziantou");
Assert.Equal("Hello Meziantou!", result);
Implements

Constructors

NameDescription
Template()

Template()

Template.cs
public Template()

No documentation is available.

Properties

NameDescription
ArgumentsGets the list of template arguments.
AssemblyReferencesGets the list of assembly references used for template compilation.
BaseClassFullTypeNameGets or sets the full type name of the base class for the generated template class.
BlocksGets the list of parsed blocks after loading a template.
DebugGets or sets a value indicating whether to compile the template in debug mode.
EndCodeBlockDelimiterGets or sets the delimiter that marks the end of a code block.
ImplementedInterfacesGets the list of interfaces implemented by the generated template class.
IncludedSourceFilesGets the list of C# source files included in the template compilation.
IsBuiltGets a value indicating whether the template has been built.
OutputParameterNameGets or sets the name of the output parameter used in the generated code.
OutputTypeGets or sets the type of the output parameter.
SourceCodeGets the generated C# source code after building the template.
SourceFileNameGets or sets the optional source file name used in compiler diagnostics.
StartCodeBlockDelimiterGets or sets the delimiter that marks the start of a code block.
ThrowOnMissingArgumentGets or sets a value indicating whether running the template with named parameters throws when an argument has no value. When false (the default), a missing argument gets the default value of its type.
UsingsGets the list of using directives.

Arguments

Template.cs

Gets the list of template arguments.

public ArgumentCollection Arguments { get; }

Property value

ArgumentCollection

AssemblyReferences

Template.cs

Gets the list of assembly references used for template compilation.

public AssemblyReferenceCollection AssemblyReferences { get; }

BaseClassFullTypeName

Template.cs

Gets or sets the full type name of the base class for the generated template class.

public string? BaseClassFullTypeName { get; set; }

Property value

string?

Gets the list of parsed blocks after loading a template.

public BlockCollection Blocks { get; }

Property value

BlockCollection

Gets or sets a value indicating whether to compile the template in debug mode.

public bool Debug { get; set; }

Property value

bool

EndCodeBlockDelimiter

Template.cs

Gets or sets the delimiter that marks the end of a code block.

public string EndCodeBlockDelimiter { get; set; }

Property value

string

ImplementedInterfaces

Template.cs

Gets the list of interfaces implemented by the generated template class.

public InterfaceCollection ImplementedInterfaces { get; }

Property value

InterfaceCollection

IncludedSourceFiles

Template.cs

Gets the list of C# source files included in the template compilation.

public FileReferenceCollection IncludedSourceFiles { get; }

Gets a value indicating whether the template has been built.

public bool IsBuilt { get; }

Property value

bool

OutputParameterName

Template.cs

Gets or sets the name of the output parameter used in the generated code.

public string? OutputParameterName { get; set; }

Property value

string?

OutputType

Template.cs

Gets or sets the type of the output parameter.

public Type? OutputType { get; set; }

Property value

Type?

SourceCode

Template.cs

Gets the generated C# source code after building the template.

public string? SourceCode { get; }

Property value

string?

SourceFileName

Template.cs

Gets or sets the optional source file name used in compiler diagnostics.

public string? SourceFileName { get; set; }

Property value

string?

StartCodeBlockDelimiter

Template.cs

Gets or sets the delimiter that marks the start of a code block.

public string StartCodeBlockDelimiter { get; set; }

Property value

string

Remarks

The delimiter written twice in the text of the template is written once to the output, and does not start a code block.

ThrowOnMissingArgument

Template.cs

Gets or sets a value indicating whether running the template with named parameters throws when an argument has no value. When false (the default), a missing argument gets the default value of its type.

public bool ThrowOnMissingArgument { get; set; }

Property value

bool

Gets the list of using directives.

public UsingCollection Usings { get; }

Property value

UsingCollection

Methods

NameDescription
Build(CancellationToken)Compiles the template into executable code.
Compile(string, CancellationToken)Compiles the source code into an assembly.
CreateAssemblyLoadContext()Creates the load context the compiled template is loaded into.
CreateClassMemberBlock(string, int)Creates a class member block for class-level members.
CreateCodeBlock(string, int)Creates a code block for executable code.
CreateCodeExpressionBlock(string, int)Creates a code block for an evaluation expression.
CreateCompilation(SyntaxTree)Creates a C# compilation from the syntax tree.
CreateDirectiveBlock(string, string, string, int)Creates a directive block.
CreateEmitOptions()Creates emit options for the compilation.
CreateIncludedSyntaxTree(string, CancellationToken)Creates a syntax tree from an included source file.
CreateMethodParameters(TextWriter, IReadOnlyDictionary<string, object?>)Creates the method parameters for template execution with named parameters.
CreateMethodParameters(TextWriter, object?[]?)Creates the method parameters for template execution.
CreateOutput(TextWriter)Creates an output object for the template.
CreateParseOptions()
CreateReferences()Creates the list of assembly references for compilation.
CreateStringWriter()Creates a string writer for capturing template output.
CreateSyntaxTree(string, CancellationToken)Creates a syntax tree from the generated source code.
CreateTextBlock(string, int)Creates a text block for text content.
Dispose()Unloads the assembly the template was compiled into.
Dispose(bool)Releases the resources used by the template.
FindMethod(Assembly)Finds the Run method in the compiled assembly.
InvokeRunMethod(object?[])Invokes the compiled Run method with the specified parameters.
Load(TextReader)Loads the template from a TextReader.
Load(string)Loads the template from a string.
LoadAssembly(MemoryStream, MemoryStream)Loads an assembly from memory streams.
Run(IReadOnlyDictionary<string, object?>)Executes the template with named parameters and returns the result.
Run(TextWriter, IReadOnlyDictionary<string, object?>)Executes the template with named parameters and writes the result to a text writer.
Run(TextWriter, object?[])Executes the template with the specified parameters and writes the result to a text writer.
Run(object?[])Executes the template with the specified parameters and returns the result.

Build(CancellationToken)

Template.cs

Compiles the template into executable code.

public void Build(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken
A cancellation token to observe.

Exceptions

ObjectDisposedException
The template is disposed.

Compile(string, CancellationToken)

Template.cs

Compiles the source code into an assembly.

protected virtual void Compile(string source, CancellationToken cancellationToken)

Parameters

source string
The C# source code to compile.
cancellationToken CancellationToken
A cancellation token to observe.

CreateAssemblyLoadContext()

Template.cs

Creates the load context the compiled template is loaded into.

protected virtual AssemblyLoadContext CreateAssemblyLoadContext()

Returns

AssemblyLoadContext A new load context. It should be collectible, otherwise the compiled template can never be unloaded.

CreateClassMemberBlock(string, int)

Template.cs

Creates a class member block for class-level members.

protected virtual ClassMemberBlock CreateClassMemberBlock(string text, int index)

Parameters

text string
The member content.
index int
The block index.

Returns

ClassMemberBlock A new ClassMemberBlock instance.

CreateCodeBlock(string, int)

Template.cs

Creates a code block for executable code.

protected virtual CodeBlock CreateCodeBlock(string text, int index)

Parameters

text string
The code content.
index int
The block index.

Returns

CodeBlock A new CodeBlock instance.

CreateCodeExpressionBlock(string, int)

Template.cs

Creates a code block for an evaluation expression.

protected virtual CodeBlock CreateCodeExpressionBlock(string text, int index)

Parameters

text string
The expression content.
index int
The block index.

Returns

CodeBlock A new CodeBlock instance.

CreateCompilation(SyntaxTree)

Template.cs

Creates a C# compilation from the syntax tree.

protected virtual CSharpCompilation CreateCompilation(SyntaxTree syntaxTree)

Parameters

syntaxTree SyntaxTree
The syntax tree to compile.

Returns

CSharpCompilation A C# compilation instance.

CreateDirectiveBlock(string, string, string, int)

Template.cs

Creates a directive block.

protected virtual DirectiveBlock CreateDirectiveBlock(string text, string name, string value, int index)

Parameters

text string
The directive content without the directive marker.
name string
The directive name.
value string
The directive value.
index int
The block index.

Returns

DirectiveBlock A new DirectiveBlock instance.

CreateEmitOptions()

Template.cs

Creates emit options for the compilation.

protected virtual EmitOptions CreateEmitOptions()

Returns

EmitOptions Emit options for the compiler.

CreateIncludedSyntaxTree(string, CancellationToken)

Template.cs

Creates a syntax tree from an included source file.

protected virtual SyntaxTree CreateIncludedSyntaxTree(string sourcePath, CancellationToken cancellationToken)

Parameters

sourcePath string
The path to the C# source file.
cancellationToken CancellationToken
A cancellation token to observe.

Returns

SyntaxTree A syntax tree for compilation.

CreateMethodParameters overloads

CreateMethodParameters(TextWriter, IReadOnlyDictionary<string, object?>)

Template.cs

Creates the method parameters for template execution with named parameters.

protected virtual object?[] CreateMethodParameters(TextWriter writer, IReadOnlyDictionary<string, object?> parameters)
Parameters
writer TextWriter
The text writer for output.
parameters IReadOnlyDictionary<string, object?>
A dictionary of parameter names and values.
Returns

object?[] An array of method parameters.

Exceptions
TemplateException
Template.ThrowOnMissingArgument is true and an argument has no value in parameters.

CreateMethodParameters(TextWriter, object?[]?)

Template.cs

Creates the method parameters for template execution.

protected virtual object[] CreateMethodParameters(TextWriter writer, object?[]? parameters)
Parameters
writer TextWriter
The text writer for output.
parameters object?[]?
The template parameter values.
Returns

object[] An array of method parameters.

CreateOutput(TextWriter)

Template.cs

Creates an output object for the template.

protected virtual object CreateOutput(TextWriter writer)

Parameters

writer TextWriter
The text writer to write output to.

Returns

object An output object.

CreateParseOptions()

Template.cs
protected virtual CSharpParseOptions CreateParseOptions()

No documentation is available.

CreateReferences()

Template.cs

Creates the list of assembly references for compilation.

protected virtual MetadataReference[] CreateReferences()

Returns

MetadataReference[] An array of metadata references.

CreateStringWriter()

Template.cs

Creates a string writer for capturing template output.

protected virtual StringWriter CreateStringWriter()

Returns

StringWriter A new string writer instance.

CreateSyntaxTree(string, CancellationToken)

Template.cs

Creates a syntax tree from the generated source code.

protected virtual SyntaxTree CreateSyntaxTree(string source, CancellationToken cancellationToken)

Parameters

source string
The C# source code.
cancellationToken CancellationToken
A cancellation token to observe.

Returns

SyntaxTree A syntax tree for compilation.

CreateTextBlock(string, int)

Template.cs

Creates a text block for text content.

protected virtual TextBlock CreateTextBlock(string text, int index)

Parameters

text string
The text content.
index int
The block index.

Returns

TextBlock A new TextBlock instance.

Dispose overloads

Dispose()

Template.cs

Unloads the assembly the template was compiled into.

public void Dispose()
Remarks

The assembly is unloaded once nothing references it anymore, which includes any object the template created. A disposed template cannot be built or run again.

Dispose(bool)

Template.cs

Releases the resources used by the template.

protected virtual void Dispose(bool disposing)
Parameters
disposing bool
true when called from Template.Dispose.

FindMethod(Assembly)

Template.cs

Finds the Run method in the compiled assembly.

protected virtual MethodInfo FindMethod(Assembly assembly)

Parameters

assembly Assembly
The compiled assembly.

Returns

MethodInfo The Run method information.

InvokeRunMethod(object?[])

Template.cs

Invokes the compiled Run method with the specified parameters.

protected virtual void InvokeRunMethod(object?[] p)

Parameters

p object?[]
The method parameters.

Load overloads

Load(TextReader)

Template.cs

Loads the template from a TextReader.

public void Load(TextReader reader)
Parameters
reader TextReader
The text reader containing the template.

Load(string)

Template.cs

Loads the template from a string.

public void Load(string text)
Parameters
text string
The template text containing code blocks.

LoadAssembly(MemoryStream, MemoryStream)

Template.cs

Loads an assembly from memory streams.

protected virtual Assembly LoadAssembly(MemoryStream peStream, MemoryStream pdbStream)

Parameters

peStream MemoryStream
The stream containing the assembly.
pdbStream MemoryStream
The stream containing debug symbols.

Returns

Assembly The loaded assembly.

Remarks

The assembly is loaded in the load context created by Template.CreateAssemblyLoadContext, so that Template.Dispose can unload it. Loading it in the default context instead, for instance with Assembly.Load, keeps it in memory for the lifetime of the process.

Run overloads

Run(IReadOnlyDictionary<string, object?>)

Template.cs

Executes the template with named parameters and returns the result.

public string Run(IReadOnlyDictionary<string, object?> parameters)
Parameters
parameters IReadOnlyDictionary<string, object?>
A dictionary of parameter names and values.
Returns

string The generated text from the template.

Run(TextWriter, IReadOnlyDictionary<string, object?>)

Template.cs

Executes the template with named parameters and writes the result to a text writer.

public virtual void Run(TextWriter writer, IReadOnlyDictionary<string, object?> parameters)
Parameters
writer TextWriter
The text writer to write the output to.
parameters IReadOnlyDictionary<string, object?>
A dictionary of parameter names and values.

Run(TextWriter, object?[])

Template.cs

Executes the template with the specified parameters and writes the result to a text writer.

public virtual void Run(TextWriter writer, params object?[] parameters)
Parameters
writer TextWriter
The text writer to write the output to.
parameters object?[]
The parameter values to pass to the template.

Run(object?[])

Template.cs

Executes the template with the specified parameters and returns the result.

public string Run(params object?[] parameters)
Parameters
parameters object?[]
The parameter values to pass to the template.
Returns

string The generated text from the template.