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

半世苍凉 提交于 2019-12-05 06:02:02

ok, the problem was I used renderer from a Singleton service (EmailerService). I changed its registration to Scoped and it all works now:

services.AddScoped<IEmailer, EmailerService>();

When a service gets injected as scoped, the dependent class must also be injected as scoped.

Unfortunately, this does not work for every use case. When creating the E-Mail service statically, you don't have an HTTP Context.

In my case, I had a scheduled Task that was executed statically by Hangfire:

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

When you need that scoped service from a static context, you have two options:

  1. use a dependency injection framework that gives you more control over the injection context. I highly recommend DryIoc.Microsoft.DependencyInjection from NuGet. (Documentation)

  2. disable the scope validation:

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!