gpt4 book ai didi

c# - 无法从根提供程序解析范围服务。 ASP.NET MVC 应用程序

转载 作者:行者123 更新时间:2023-12-03 16:37:19 27 4
gpt4 key购买 nike

我正在使用 Adam Freeman 的 Pro ASP.NET Core MVC 第 6 版做商店应用程序。书中的例子是用Core 1.0制作的,我使用的是Core 3.0。在尝试将数据播种到我的数据库(entityFramework)时,出现如下错误。

System.InvalidOperationException: 'Cannot resolve scoped service 'BookStore.Models.ApplicationDbContext' from root provider.'



下面是我的代码:
 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
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>();
});
}

我在依赖注入(inject)方面相当新,所以对正在发生的事情进行一些解释会很好。我在网上搜索了两个多小时没有任何结果。

更多关于错误的信息:

at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope) at Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at BookStore.Models.SeedData.EnsurePopulated(IApplicationBuilder app) in C:\Users\Piotr\source\repos\Store\BookStore\Models\SeedData.cs:line 12 at BookStore.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context) in C:\Users\Piotr\source\repos\Store\BookStore\Startup.cs:line 51 at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder) at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.b__0(IApplicationBuilder builder) at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass13_0.b__2(IApplicationBuilder app) at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.g__MiddlewareFilterBuilder|0(IApplicationBuilder builder) at Microsoft.AspNetCore.Server.IIS.Core.IISServerSetupFilter.<>c__DisplayClass2_0.b__0(IApplicationBuilder app) at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder app) at Microsoft.AspNetCore.Hosting.GenericWebHostService.d__31.MoveNext()



所以解决方案是:
var scopeeee = app.ApplicationServices.CreateScope();

ApplicationDbContext context = scopeeee.ServiceProvider.GetRequiredService<ApplicationDbContext>();

在 EnsurePopulated 方法的开头添加。谢谢!

最佳答案

您需要在 EnsurePopulated 中创建范围方法,然后从此范围中获取实例。

关于c# - 无法从根提供程序解析范围服务。 ASP.NET MVC 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59903641/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com