无法解析来自根提供商的作用域服务 Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.IViewBufferScope

Cannot resolve scoped service Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.IViewBufferScope from root provider

我正在尝试在我的 ASP.NET Core 2.0 网络应用程序中使用此示例 RazorViewEngineEmailTemplates 从视图创建 html 电子邮件正文。但是当我 运行 它和我的控制器收到 ajax 请求时,我得到这个错误:

Cannot resolve scoped service Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.IViewBufferScope from root provider

它可能来自解决 RazorViewToStringRenderer class 中的依赖关系,但我不知道如何解决这个问题。

好的,问题是我使用了单例服务 (EmailerService) 中的渲染器。我将其注册更改为 Scoped,现在一切正常:

services.AddScoped<IEmailer, EmailerService>();

当服务作为范围注入时,相关的 class 也必须作为范围注入。

不幸的是,这并不适用于所有用例。静态创建 E-Mail 服务时,您没有 HTTP 上下文。

在我的例子中,我有一个由 Hangfire 静态执行的计划任务:

var mailer = ServiceProviderSinleton.Instance.GetService(typeof(IEmailer))

当您需要来自静态上下文的范围服务时,您有两个选择:

  1. 使用依赖注入框架,让您更好地控制注入上下文。我强烈推荐 NuGet 的 DryIoc.Microsoft.DependencyInjection。 (Documentation)

  2. 禁用范围验证:

return WebHost.CreateDefaultBuilder()
    .ConfigureLogging(builder => builder.AddSerilog(Log.Logger, dispose: true))
    .UseKestrel(options => options.ConfigureEndpoints(configuration))
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseStartup<TStartup>()
    .UseSerilog()
    .UseDefaultServiceProvider(options => options.ValidateScopes = false)
    .Build();