关于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

posted @ 2024-04-18 00:21  BloggerSb  阅读(334)  评论(0编辑  收藏  举报