Template Class
Represents a text template with embedded code blocks that can be dynamically compiled and executed.
public class Template : IDisposableRemarks
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
| Name | Description |
|---|---|
| Template() |
Template()
Template.cspublic Template()No documentation is available.
Properties
| Name | Description |
|---|---|
| Arguments | Gets the list of template arguments. |
| AssemblyReferences | Gets the list of assembly references used for template compilation. |
| BaseClassFullTypeName | Gets or sets the full type name of the base class for the generated template class. |
| Blocks | Gets the list of parsed blocks after loading a template. |
| Debug | Gets or sets a value indicating whether to compile the template in debug mode. |
| EndCodeBlockDelimiter | Gets or sets the delimiter that marks the end of a code block. |
| ImplementedInterfaces | Gets the list of interfaces implemented by the generated template class. |
| IncludedSourceFiles | Gets the list of C# source files included in the template compilation. |
| IsBuilt | Gets a value indicating whether the template has been built. |
| OutputParameterName | Gets or sets the name of the output parameter used in the generated code. |
| OutputType | Gets or sets the type of the output parameter. |
| SourceCode | Gets the generated C# source code after building the template. |
| SourceFileName | Gets or sets the optional source file name used in compiler diagnostics. |
| StartCodeBlockDelimiter | Gets or sets the delimiter that marks the start of a code block. |
| ThrowOnMissingArgument | 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. |
| Usings | Gets the list of using directives. |
Arguments
Template.csAssemblyReferences
Template.csGets the list of assembly references used for template compilation.
public AssemblyReferenceCollection AssemblyReferences { get; }Property value
BaseClassFullTypeName
Template.csBlocks
Template.csGets the list of parsed blocks after loading a template.
public BlockCollection Blocks { get; }Property value
Debug
Template.csEndCodeBlockDelimiter
Template.csImplementedInterfaces
Template.csGets the list of interfaces implemented by the generated template class.
public InterfaceCollection ImplementedInterfaces { get; }Property value
IncludedSourceFiles
Template.csGets the list of C# source files included in the template compilation.
public FileReferenceCollection IncludedSourceFiles { get; }Property value
IsBuilt
Template.csOutputParameterName
Template.csOutputType
Template.csSourceCode
Template.csSourceFileName
Template.csStartCodeBlockDelimiter
Template.csThrowOnMissingArgument
Template.csUsings
Template.csMethods
| Name | Description |
|---|---|
| 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.csCompiles the template into executable code.
public void Build(CancellationToken cancellationToken)Parameters
cancellationTokenCancellationToken- A cancellation token to observe.
Exceptions
ObjectDisposedException- The template is disposed.
Compile(string, CancellationToken)
Template.csCompiles the source code into an assembly.
protected virtual void Compile(string source, CancellationToken cancellationToken)Parameters
sourcestring- The C# source code to compile.
cancellationTokenCancellationToken- A cancellation token to observe.
CreateAssemblyLoadContext()
Template.csCreates 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.csCreates a class member block for class-level members.
protected virtual ClassMemberBlock CreateClassMemberBlock(string text, int index)CreateCodeBlock(string, int)
Template.csCreateCodeExpressionBlock(string, int)
Template.csCreateCompilation(SyntaxTree)
Template.csCreates a C# compilation from the syntax tree.
protected virtual CSharpCompilation CreateCompilation(SyntaxTree syntaxTree)Parameters
syntaxTreeSyntaxTree- The syntax tree to compile.
Returns
CSharpCompilation A C# compilation instance.
CreateDirectiveBlock(string, string, string, int)
Template.csCreates a directive block.
protected virtual DirectiveBlock CreateDirectiveBlock(string text, string name, string value, int index)Parameters
textstring- The directive content without the directive marker.
namestring- The directive name.
valuestring- The directive value.
indexint- The block index.
Returns
DirectiveBlock A new DirectiveBlock instance.
CreateEmitOptions()
Template.csCreates emit options for the compilation.
protected virtual EmitOptions CreateEmitOptions()Returns
EmitOptions Emit options for the compiler.
CreateIncludedSyntaxTree(string, CancellationToken)
Template.csCreates a syntax tree from an included source file.
protected virtual SyntaxTree CreateIncludedSyntaxTree(string sourcePath, CancellationToken cancellationToken)Parameters
sourcePathstring- The path to the C# source file.
cancellationTokenCancellationToken- A cancellation token to observe.
Returns
SyntaxTree A syntax tree for compilation.
CreateMethodParameters overloads
CreateMethodParameters(TextWriter, IReadOnlyDictionary<string, object?>)
Template.csCreates the method parameters for template execution with named parameters.
protected virtual object?[] CreateMethodParameters(TextWriter writer, IReadOnlyDictionary<string, object?> parameters)Parameters
writerTextWriter- The text writer for output.
parametersIReadOnlyDictionary<string, object?>- A dictionary of parameter names and values.
Returns
object?[] An array of method parameters.
Exceptions
TemplateExceptionTemplate.ThrowOnMissingArgumentistrueand an argument has no value inparameters.
CreateMethodParameters(TextWriter, object?[]?)
Template.csCreates the method parameters for template execution.
protected virtual object[] CreateMethodParameters(TextWriter writer, object?[]? parameters)Parameters
writerTextWriter- The text writer for output.
parametersobject?[]?- The template parameter values.
Returns
object[] An array of method parameters.
CreateOutput(TextWriter)
Template.csCreates an output object for the template.
protected virtual object CreateOutput(TextWriter writer)CreateParseOptions()
Template.csCreateReferences()
Template.csCreates the list of assembly references for compilation.
protected virtual MetadataReference[] CreateReferences()Returns
MetadataReference[] An array of metadata references.
CreateStringWriter()
Template.csCreates a string writer for capturing template output.
protected virtual StringWriter CreateStringWriter()Returns
StringWriter A new string writer instance.
CreateSyntaxTree(string, CancellationToken)
Template.csCreates a syntax tree from the generated source code.
protected virtual SyntaxTree CreateSyntaxTree(string source, CancellationToken cancellationToken)Parameters
sourcestring- The C# source code.
cancellationTokenCancellationToken- A cancellation token to observe.
Returns
SyntaxTree A syntax tree for compilation.
CreateTextBlock(string, int)
Template.csDispose overloads
Dispose()
Template.csUnloads 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.csReleases the resources used by the template.
Parameters
disposingbooltruewhen called fromTemplate.Dispose.
FindMethod(Assembly)
Template.csFinds the Run method in the compiled assembly.
protected virtual MethodInfo FindMethod(Assembly assembly)InvokeRunMethod(object?[])
Template.csLoad overloads
Load(TextReader)
Template.csLoads the template from a TextReader.
public void Load(TextReader reader)Parameters
readerTextReader- The text reader containing the template.
Load(string)
Template.csLoadAssembly(MemoryStream, MemoryStream)
Template.csLoads an assembly from memory streams.
protected virtual Assembly LoadAssembly(MemoryStream peStream, MemoryStream pdbStream)Parameters
peStreamMemoryStream- The stream containing the assembly.
pdbStreamMemoryStream- 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.csExecutes the template with named parameters and returns the result.
public string Run(IReadOnlyDictionary<string, object?> parameters)Parameters
parametersIReadOnlyDictionary<string, object?>- A dictionary of parameter names and values.
Returns
string The generated text from the template.
Run(TextWriter, IReadOnlyDictionary<string, object?>)
Template.csExecutes the template with named parameters and writes the result to a text writer.
public virtual void Run(TextWriter writer, IReadOnlyDictionary<string, object?> parameters)Parameters
writerTextWriter- The text writer to write the output to.
parametersIReadOnlyDictionary<string, object?>- A dictionary of parameter names and values.
Run(TextWriter, object?[])
Template.csExecutes the template with the specified parameters and writes the result to a text writer.
public virtual void Run(TextWriter writer, params object?[] parameters)Parameters
writerTextWriter- The text writer to write the output to.
parametersobject?[]- The parameter values to pass to the template.