Search code examples
c#.netrazorrazorengine

How to create RazorEngineHost for RazorTemplateEngin in non MVC project


I'm using RazorEngine in an Console application.

I want to initialise RazorEngineHost and pass into RazorTemplateEngin. However as I can see in MSDN documentations it says RazorEngineHost "is not intended to be used directly from your code".RazorEngineHost

So what is the best way of creating RazorTemplateEngin?

This question quite different from How to use Razor View Engine in a console application?> I want to use RazorTemplateEngin becuse I have template not string.


Solution

  • If you have a look at RazorTemplateEngine on MSDN you can see that the documentation for that also says "not intended to be used directly from your code", that doesn't mean that you can't. If you want to use an instance of RazorTemplateEngineyou have to pass in a RazorEngineHost instance. Have a look at this blog post for usage: Leveraging Razor Templates Outside of ASP.NET

    var language = new CSharpRazorCodeLanguage();
    var host = new RazorEngineHost(language) {
       DefaultBaseClass = "OrderInfoTemplateBase",
       DefaultClassName = "OrderInfoTemplate",
       DefaultNamespace = "CompiledRazorTemplates",
    };
    
    host.NamespaceImports.Add("System");
    

    To begin, the RazorEngineHost’s constructor accepts a RazorCodeLanguage specifying the target template’s code language. This example produces a host that can parse Razor templates written using C#. To support templates written in Visual Basic, supply a VBRazorCodeLanguage instance instead. The additional initializer properties instruct the code generator to emit code with a particular class name, deriving from a custom template base class, and residing in a particular namespace. Finally, add the System namespace to the list of imported namespaces required for the generated class to compile just as you would import a namespace in a normal, hand-written class.