關於Cannot resolve scoped service from root provider解決方案

BloggerSb發表於2024-04-18

在靜態類或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

相關文章