问题描述
我正在使用Adam Freeman的Pro ASP.NET Core MVC 6th Edition做商店应用程序.书中的示例是在Core 1.0中制作的,而我正在使用Core 3.0.尝试将数据播种到数据库(entityFramework)时,出现以下错误.
I am doing Store application with Pro ASP.NET Core MVC 6th Edition by Adam Freeman. The example in book is made in Core 1.0, and I am using Core 3.0. I get error as below, while trying to seed data to my database (entityFramework).
下面是我的代码:
public class SeedData
{
public static void EnsurePopulated(IApplicationBuilder app)
{
ApplicationDbContext context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>();
if (!context.Products.Any())
{
context.Products.AddRange(
new Product {
Name = "Witcher",
Description = "Geralt the Witcher",
Category = "Fantasy",
Price = 30 }
);
context.SaveChanges();
}
}
启动类:
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration, Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
{
Configuration = new ConfigurationBuilder().SetBasePath(env.ContentRootPath).AddJsonFile("appsettings.json").Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:BookStoreProducts:ConnectionString"]));
services.AddTransient<IProductRepository, EFProductRepository>();
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Product}/{action=List}/{id?}");
});
SeedData.EnsurePopulated(app);
}
}
和Program.cs
And Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
我在依赖注入方面还比较陌生,因此可以对发生的情况进行一些解释.我在网上搜索答案超过两个小时,没有任何结果.
I am rather new in dependency injection so some explanation what is happening would be nice. I am searchin answer online for more than two hours without any result.
有关错误的更多信息:
因此解决方案是:
var scopeeee = app.ApplicationServices.CreateScope();
ApplicationDbContext context = scopeeee.ServiceProvider.GetRequiredService<ApplicationDbContext>();
在确保方法的开头添加.谢谢!
Added at the beggining of EnsurePopulated method. Thanks!
推荐答案
您需要在EnsurePopulated
方法中创建范围,然后从该范围中获取实例.
You need to create scope in EnsurePopulated
method and then get instance from this scope.
这篇关于无法从根提供者解析作用域服务. ASP.NET MVC应用程序App的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!