关于Cannot resolve scoped service from root provider解决方案
在静态类或ServiceProvider
来至于静态属性或类已AddSingleton
的方式添加进IServiceCollection
,此时调用service.GetService<ICoreRepository>()
,则会出现Cannot resolve scoped service from root provider
异常
解决方法:在调用时如下使用
public static class SeedData { public static void Initialize(IServiceProvider serviceProvider) { using (var serviceScope = serviceProvider.CreateScope()) //手动高亮 { var dbContext = serviceScope.ServiceProvider.GetService<BlogDbContext>(); //手动高亮 if (dbContext.Database.EnsureCreated() || !dbContext.Set<User>().Any()) { var user = new User { DisplayName = "BugChang", Password = "000000..", UserName = "BugChang" }; dbContext.Set<User>().Add(user); dbContext.SaveChanges(); } } } }
https://www.jianshu.com/p/8e928947d833
此随笔或为自己所写、或为转载于网络。仅用于个人收集及备忘。