簡體   English   中英

無法從根提供程序解析范圍服務。 ASP.NET MVC 應用程序

[英]Cannot resolve scoped service from root provider. ASP.NET MVC app App

我正在使用 Adam Freeman 的 Pro ASP.NET Core MVC 6th Edition 做 Store 應用程序。 書中的例子是用Core 1.0制作的,我使用的是Core 3.0。 在嘗試將數據播種到我的數據庫 (entityFramework) 時,出現如下錯誤。

System.InvalidOperationException: '無法從根提供程序解析范圍服務 'BookStore.Models.ApplicationDbContext'。

下面是我的代碼:

 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>();
            });
}

我在依賴注入方面比較新,所以對正在發生的事情進行一些解釋會很好。 我在網上搜索了兩個多小時的答案,沒有任何結果。

以及更多關於錯誤的信息:

在 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope) at Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve, IServiceScope rootScope) Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
在 Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredServiceProvider[T](T)在 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 上下文)在 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 ) 在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo 文化)
在 Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder) 在 Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.b__0(IApplicationBuilder builder) 在 Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass13_0.b__2( IApplicationBuilder 應用程序)在 Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)在 Microsoft.AspNetCore.Server.IIS.Core.IISServerSetupFilter.<>c__DisplayClass2_0.b__0(IApplicationBuilder 應用程序)在 Microsoft。 AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder 應用程序) 在 Microsoft.AspNetCore.Hosting.GenericWebHostService.d__31.MoveNext()

所以解決方案是:

var scopeeee = app.ApplicationServices.CreateScope();

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

在EnsurePopulated 方法開始時添加。 謝謝!

您需要在EnsurePopulated方法中創建作用域,然后從該作用域中獲取實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM