Skip to content

@Inject and referencing other assemblies

Alexander edited this page Mar 18, 2020 · 6 revisions

If you need to inject assemblies in your template mosly likely you are overengeneering or doing it wrong

Intended use of external code

Maintainer belives templates should stay nice and clean without dependencies, all extras should be provided and handled my TemplateBase

Localizer example

public class MyTemplateBase : RazorEngineTemplateBase
{
    private IStringLocalizer localizer;

    public void Initialize(IStringLocalizer localizer)
    {
        this.localizer = localizer;
    }

    public string Localize(string key)
    {
        return this.localizer[key];
    }
}
string templateText = @"

    <h1>@Localize(""Header"")</h1>

";
RazorEngine razorEngine = new RazorEngine();
RazorEngineCompiledTemplate<MyTemplateBase> compiledTemplate = razorEngine.Compile<MyTemplateBase>(templateText);

string result = compiledTemplate.Run(instance =>
{
    instance.Initialize(this.localizerInstance); // get instance from whatever source
});

Linking assemblies

In the unlikely event of water landing trying to reference external assembly, you need to explicitly link it on Compilation

RazorEngine razorEngine = new RazorEngine();
RazorEngineCompiledTemplate compiledTemplate = razorEngine.Compile(templateText, builder =>
{
    builder.AddAssemblyReferenceByName("System.Security"); // by name
    builder.AddAssemblyReference(typeof(System.IO.File)); // by type
    builder.AddAssemblyReference(Assembly.Load("source")); // by reference
});

string result = compiledTemplate.Run(new { name = "Hello" });
```cs
Clone this wiki locally