alv*_*peo 6 c# asp.net-core asp.net-core-2.0
我试图在我的ASP.NET Core 2.0 Web应用程序中使用此示例RazorViewEngineEmailTemplates从View创建一个html电子邮件正文.但是当我运行它并且我的控制器获得ajax请求时,我收到此错误:
无法从根提供程序解析范围服务Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.IViewBufferScope
它可能来自解析RazorViewToStringRenderer类中的依赖项,但我不知道如何解决这个问题.
好吧,问题是我在Singleton服务(EmailerService)中使用了渲染器.我将其注册更改为Scoped,现在一切正常:
services.AddScoped<IEmailer, EmailerService>();
Run Code Online (Sandbox Code Playgroud)
当服务作为作用域注入时,依赖类也必须作为作用域注入。
不幸的是,这并不适用于每个用例。静态创建电子邮件服务时,您没有 HTTP 上下文。
就我而言,我有一个由 Hangfire 静态执行的计划任务:
var mailer = ServiceProviderSinleton.Instance.GetService(typeof(IEmailer))
Run Code Online (Sandbox Code Playgroud)
当您需要静态上下文中的范围服务时,您有两个选择:
使用依赖注入框架,让您可以更好地控制注入上下文。我强烈推荐DryIoc.Microsoft.DependencyInjection来自 NuGet。(文档)
禁用范围验证:
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3151 次 |
| 最近记录: |