Skip to content

@Inject and referencing other assemblies

Alexander Selishchev edited this page Oct 22, 2026 · 7 revisions

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

Intended use of external code

The maintainer believes templates should stay nice and clean, without dependencies. All extras should be provided and handled by the template base class.

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 a water landing need to reference an external assembly, you have to explicitly link it at 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" });

Clone this wiki locally