我已經看到了一些關於這方面的類似例子,但我對這門語言還不夠了解,只是還沒有看到我做錯了什麼。我拼湊了一個演示來了解更多信息,但我在播種我的數據庫時遇到了麻煩。ASP.NET核心2種子數據庫
我收到以下錯誤:
InvalidOperationException: Cannot resolve scoped service 'demoApp.Models.AppDbContext' from root provider.
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, ServiceProvider serviceProvider)
這裏有三個文件有問題:
型號/ AppDbContext.cs
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Product> Products{ get; set; }
public DbSet<Category> Categories { get; set; }
}
型號/ DBInitializer.cs
public static class DbInitializer
{
public static void Seed(IApplicationBuilder applicationBuilder)
{
//I'm bombing here
AppDbContext context = applicationBuilder.ApplicationServices.GetRequiredService<AppDbContext>();
if (!context.Products.Any())
{
// Add range of products
}
context.SaveChanges();
}
private static Dictionary<string, Category> _categories;
public static Dictionary<string, Category> Categories
{
get
{
if (_categories == null)
{
// Add categories...
}
return _categories;
}
}
}
Startup.cs
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ICategoryRepository, CategoryRepository>();
services.AddTransient<IProductRepository, ProductRepository>();
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseStatusCodePages();
// Kersplat!
DbInitializer.Seed(app);
}
else ...
app.UseStaticFiles();
app.UseMvc(routes => {...});
}
有人能幫忙解釋一下我做錯了,如何補救?
爲什麼修改'Main'?有沒有提到這是最好的參考? –
I t在上面的代碼下面的鏈接文章中提到它。 「在較老的教程中,您可能會在Startup.cs中的Configure方法中看到類似的代碼,我們建議您僅使用Configure方法來設置請求管道,應用程序啓動代碼屬於Main方法。 – palehorse
注意:爲使CreateScope方法可用,需要使用以下using語句:'using Microsoft.Extensions.DependencyInjection;'。 – JohnLBevan