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