Using the RazorStringHostContainer Class

RazorStringHostContainer executes templates from string, but caches compiled templates based on the template's content. IOW, running the same exact template twice will automatically compile on the first run, and use the cached version on the second and subsequent runs. As long as the the template string is identical the cached assembly is used.

To run a String Template Host:

var host = new RazorStringHostContainer();
//host.UseAppDomain = true; 
        
// add model assembly - ie. this assembly
host.AddAssemblyFromType(this);
host.AddAssembly("System.Data.dll");
    
// must start the host container
host.Start();
              
// Create a model to pass in
Person person = new Person()
{
    Name = "Rick",
    Company = "West Wind",
    Entered = DateTime.Now,
    Address = new Address()
    {
        Street = "32 Kaiea",
        City = "Paia"
    }
};

// create a template to render
string template = @"@inherits Westwind.RazorTemplateBase<RazorHostingTests.Person>
<b>@Model.Name of @Model.Company entered on @Model.Entered";
    
// Render the actual template and pass the model
string result = host.RenderTemplate(string,person);
    	
Console.WriteLine(result);
Console.WriteLine("---");
Console.WriteLine(host.Engine.LastGeneratedCode);

if (result == null)
    Assert.Fail(host.ErrorMessage);

// shut down the host            
host.Stop();

// Hosts also implement IDisposable to Stop
host.Dispose();  

With a host container you typically will run many requests between the Start() and Stop() operations.

String Template Caching

The StringHostContainer caches templates between executions in a collection of compiled assemblies that are re-executed if you pass the same string template to be processed. Changing the template causes the template to be recompiled, and a new assembly to be created and cached.

Caching only works effectively if you keep a reference to the HostContainer alive for the duration of your application or subcomponent. Ideally you'll want to use static/Singleton instance for your host container in your application to ensure the container and the cached templates and assemblies stick around.


© West Wind Technologies, 2018 • Updated: 05/29/17
Comment or report problem with topic