在评论中
this provided answer from the link provided
您声明
我没办法让它工作。我收到错误:无法解析“Microsoft”类型的服务。AspNetCore。Mvc。剃须刀IRazorViewEngine“正在尝试激活”Mvc。RenderViewToString。RazorViewToStringRender“.”
这通常表示所需的服务未在服务集合中注册,因此提供程序无法在需要时解析该服务。
该答案没有提及其他服务配置,只有
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IViewRender, ViewRender>();
}
因为它已经在Asp中运行。Net核心环境,这意味着在控制台应用程序中手动添加的服务已经在启动时完成。
请注意以下代码段
the answer
这是从您评论的答案中链接到的。
private static void ConfigureDefaultServices(IServiceCollection services) {
var applicationEnvironment = PlatformServices.Default.Application;
services.AddSingleton(applicationEnvironment);
var appDirectory = Directory.GetCurrentDirectory();
var environment = new HostingEnvironment
{
WebRootFileProvider = new PhysicalFileProvider(appDirectory),
ApplicationName = "RenderRazorToString"
};
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>();
}
以上重要部分是
services.AddMvc();
这将向服务集合添加相关的视图引擎依赖项
MvcServiceCollectionExtensions.cs
public static IMvcBuilder AddMvc(this IServiceCollection services) {
builder.AddFormatterMappings();
builder.AddViews();
builder.AddRazorViewEngine();
builder.AddRazorPages();
builder.AddCacheTagHelper();
}
目前呈现的所有其他内容都是合理的,应该按照预期工作。
你应该复习
https://github.com/aspnet/Entropy/tree/93ee2cf54eb700c4bf8ad3251f627c8f1a07fb17/samples/Mvc.RenderViewToString
并遵循类似的结构使代码在您的场景中工作。从那里,您可以开始进行自定义修改,并监视其中断的位置。
的模块化性质。Net Core允许这样的定制,因为不同的模块可以剥离出来并在其他环境中使用。