Cannot resolve scoped service 'XXX' from root provider

Posted xtjatswc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Cannot resolve scoped service 'XXX' from root provider相关的知识,希望对你有一定的参考价值。

开发环境: asp.net core 2.2
在asp.net Core项目中需要在startup启动类中使用DbContext对数据库做一些操作,例如初始化部分基础数据.
项目中使用的数据库为sql server.
首先在Startup启动类 ConfigureServices 方法中添加DbContext:

// 添加数据库上下文

services.AddDbContext<ZYDBContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("Default")); 
});

 


然后在后续使用的时候可以通过如下方法获取注入的DbContext

new ZYDBContext(IApplicationBuilder.ApplicationServices.GetRequiredService<DbContextOptions<ZYDBContext>>());

 


但是在asp.net core 1.X 上这样可以正常的获得DbContext.但是在2.X会出现如下错误:

InvalidOperationException: Cannot resolve scoped service ‘Microsoft.EntityFrameworkCore.DbContextOptions`1[EntityFrameworkCore.ZYDBContext]‘ from root provider.
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)


网上查了资料解决方案是,在Program类中加入如下代码:

.UseDefaultServiceProvider(options =>
{
options.ValidateScopes = false;
})

 

以上是关于Cannot resolve scoped service 'XXX' from root provider的主要内容,如果未能解决你的问题,请参考以下文章

org.junit.Test 注解失效的问题The import org.junit cannot be resolved

Cannot resolve class or package ‘jdbc‘

Cannot resolve class or package ‘jdbc‘

pom.xml Cannot resolve mysql:mysql-connector-java:8.0.25

Goland下cannot resolve directory

Cannot resolve symbol ‘Component’ & Cannot resolve symbol ‘PropTypes’