Using Razor in a Console Application (outside of ASP.NET Core MVC)

Razor in a Console ApplicationIn addition up to my previous post, Using ASP.NET Core Razor Views from a Class Library,  I wanted to also dig into how you can use Razor in a Console Application.  Basically from outside of ASP.NET Core MVC.

The most likely situation for this is wanting to generate Emails using Razor that are being sent from a service or console application.  The other might be from another web framework/middleware inside of ASP.NET Core.

To demo how to use Razor outside of ASP.NET CORE MVC, I’m going to use Razor in a Console Application.  Specifically I’m using netcoreapp2.1 for this demo but you can use anything netstandard2.0.

If you’re looking at rendering Razor views from ASP.NET Core MVC for the purpose of generating email content, I recommend checking out Scott Sauber’s blog post: Walkthrough: Creating an HTML Email Template with Razor and Razor Class Libraries and Rendering it from a .NET Standard Class Library.

RazorViewStringRenderer

The heart of the code is actually from RazorViewToStringRenderer.cs in the aspnet/Entropy repo on GitHub.  This repo is for:

A chaotic experimental playground for new features and ideas – check here for small and simple samples for individual features.

NuGet Packages

In our Console App, you’ll need the following packages:

<PackageReference Include=”Microsoft.AspNetCore.Hosting” Version=”2.1.1″ />
<PackageReference Include=”Microsoft.Extensions.FileProviders.Physical” Version=”2.1.1″ />
<PackageReference Include=”Microsoft.Extensions.PlatformAbstractions” Version=”1.1.0″ />

Instantiating

In order to generate a new instance of the RazorViewToStringRenderer class, the simpliest way I’ve found is to create a ServiceCollection and AddMvc() along with a few others.

If you plan on taking this code, you might want to only generate a single instance and reuse it through your application as generating it is fairly costly.

Emails

As mentioned with using Razor for emails, I highly recommend checking out Scott Sauber’s blog post: Walkthrough: Creating an HTML Email Template with Razor and Razor Class Libraries and Rendering it from a .NET Standard Class Library.  It has everything you need to get setup using Razor to generate emails when using ASP.NET Core MVC.

Source

All of the source code for this sample is up in my AspNetCore.Razor.ClassLibrary.Demo repo on GitHub.

If you have any comments or suggestions, please let me know in the comments or on Twitter.

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.