-
Notifications
You must be signed in to change notification settings - Fork 93
@Inject and referencing other assemblies
Alexander edited this page Mar 18, 2020
·
6 revisions
If you need to inject assemblies in your template most likely you are overengineering or doing it wrong
Maintainer believes templates should stay nice and clean without dependencies, all extras should be provided and handled my TemplateBase
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
});
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