Skip to content

@Inject and referencing other assemblies

robalarcon edited this page Feb 15, 2024 · 6 revisions

If you need to inject assemblies in your template most likely you are overengineering or doing it wrong

Intended use of external code

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

Localizer as public property

public class MyTemplateBase : RazorEngineTemplateBase
{
    public IStringLocalizer Localizer;
}
string templateText = @"

    <h1>@Localizer[""Header""]</h1>

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

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

Localizer as method

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>

";
IRazorEngine razorEngine = new RazorEngine();
IRazorEngineCompiledTemplate<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

IRazorEngine razorEngine = new RazorEngine();
IRazorEngineCompiledTemplate 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" });