簡體   English   中英

無法從根提供程序解析范圍服務 - 錯誤的解決方案?

[英]Cannot resolve scoped service from root provider - solution to error?

我正在使用 .Net MVC 編寫一個應用程序,以將數據庫中的數據打印到頁面上。 我已經安裝了 EntityFrameworkCore SqlServer 包和 EntityFrameworkCore Tools 包,創建了一些數據庫類,創建了一個存儲庫類並創建並應用了數據庫遷移。

但是,當我嘗試運行該行時:

ApplicationDbContext context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>()

我收到一個錯誤:“System.InvalidOperationException: 'Cannot resolve scoped service 'SportsStore.Models.ApplicationDbContext' from root provider.'”

我知道這與解決程序范圍有關,但我不確定要進行哪些代碼更改。

這是完整的文件 SeedData.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.Extensions.DependencyInjection;
    
    namespace SportsStore.Models
    {
        public static class SeedData
        {
            public static void EnsurePopulated(IApplicationBuilder app)
            {
                ApplicationDbContext context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>();
                if (!context.Products.Any())
                {
                    context.Products.AddRange(
                        new Product
                        {
                            Name = "Kayak",
                            Description = "A boat for one person",
                            Category = "Watersports",
                            Price = 275
                        },
                        new Product
                        {
                            Name = "Lifejacket",
                            Description = "Protective and fashionable",
                            Category = "Watersports", Price = 48.95m
                        },
                        new Product
                        {
                            Name = "Soccer Ball",
                            Description = "FIFA-approved size and weight",
                            Category = "Soccer", Price = 19.50m
                        },
                        new Product
                        {
                            Name = "Corner Flags",
                            Description = "Give your playing field a professional touch",
                            Category = "Soccer",
                            Price = 34.95m
                        },
                        new Product
                        {
                            Name = "Stadium",
                            Description = "Flat-packed 35,000-seat stadium",
                            Category = "Soccer",
                            Price = 79500
                        },
                        new Product
                        {
                            Name = "Thinking Cap",
                            Description = "Improve brain efficiency by 75%",
                            Category = "Chess",
                            Price = 16
                        },
                        new Product
                        {
                            Name = "Unsteady Chair",
                            Description = "Secretly give your opponent a disadvantage",
                            Category = "Chess",
                            Price = 75
                        },
                        new Product
                        {
                            Name = "Bling-Bling King",
                            Description = "Gold-plated, diamond-studded King",
                            Category = "Chess",
                            Price = 1200
                        }
                    );
                    context.SaveChanges();
                }
            }
        }
    }

這是我的數據庫上下文類 ApplicationDbContext.cs


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.EntityFrameworkCore;
    
    namespace SportsStore.Models
    {
        public class ApplicationDbContext : DbContext 
        {
            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
                : base(options) {} // provides access to Entity Framework Core's underlying functionality
    
            public DbSet<Product> Products { get; set; } // Provides access to the Product objects in the database.
        }
    }

// 存儲庫類 - EFProductRepository.cs


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace SportsStore.Models{
        public class EFProductRepository : IProductRepository
        {
            private ApplicationDbContext context;
    
            public EFProductRepository(ApplicationDbContext ctx)
            {
                context = ctx;
            }
            public IEnumerable<Product> Products => context.Products; // maps the products property defined by IProductRepository onto Products property defined by the ApplicationDbContext class.
        }
    }

// 啟動.cs


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using SportsStore.Models;
    using Microsoft.Extensions.Configuration;
    using Microsoft.EntityFrameworkCore;
    
    namespace SportsStore
    {
        public class Startup
        {
            IConfigurationRoot Configuration;
    
            public Startup(IHostEnvironment env)
            {
                Configuration = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json").Build();
            }
    
    
    
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(
                        Configuration["Data:SportStoreProducts:ConnectionString"])); // loads configuration settings in the appsettings.json file and makes them available through a property called Configuration.
                    services.AddTransient<IProductRepository,
                    EFProductRepository>();
                services.AddMvc(options => options.EnableEndpointRouting = false);
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseStatusCodePages();
                    app.UseStaticFiles();
                }
    
                app.UseRouting();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Product}/{action=List}/{id?}");
                });
                SeedData.EnsurePopulated(app);
            }
        }
    }

如果有任何有用的建議,請告訴我! 謝謝,

問候,

羅伯特

英國倫敦

您需要在Program類中禁用范圍驗證:

public class Program {
...

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseDefaultServiceProvider(options =>
            options.ValidateScopes = false)
        .Build();
}

暫無
暫無

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

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