Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Last active July 12, 2018 01:37
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dcomartin/137e45523fec86ef604f246c6f8872d3 to your computer and use it in GitHub Desktop.
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using ClassLibrary;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.ObjectPool;
using Microsoft.Extensions.PlatformAbstractions;
namespace Console
{
class Program
{
static async Task Main(string[] args)
{
var renderer = GetRenderer();
var html = await renderer.RenderViewToStringAsync("/Myview.cshtml", new MyModel());
System.Console.Write(html);
System.Console.ReadKey();
}
private static RazorViewToStringRenderer GetRenderer()
{
var services = new ServiceCollection();
var applicationEnvironment = PlatformServices.Default.Application;
services.AddSingleton(applicationEnvironment);
var appDirectory = Directory.GetCurrentDirectory();
var environment = new HostingEnvironment
{
ApplicationName = Assembly.GetEntryAssembly().GetName().Name
};
services.AddSingleton<IHostingEnvironment>(environment);
services.Configure<RazorViewEngineOptions>(options =>
{
options.FileProviders.Clear();
options.FileProviders.Add(new PhysicalFileProvider(appDirectory));
});
services.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();
var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
services.AddSingleton<DiagnosticSource>(diagnosticSource);
services.AddLogging();
services.AddMvc();
services.AddSingleton<RazorViewToStringRenderer>();
var provider = services.BuildServiceProvider();
return provider.GetRequiredService<RazorViewToStringRenderer>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment