【问题标题】:Cannot resolve scoped service from root provider - solution to error?无法从根提供商解析范围服务 - 错误解决方案?
【发布时间】:2021-01-04 03:36:38
【问题描述】:

我正在使用 .Net MVC 编写应用程序,以将数据库中的数据打印到页面上。我已经安装了 EntityFrameworkCore SqlServer 包和 EntityFrameworkCore Tools 包,创建了一些数据库类,创建了一个存储库类并创建并应用了数据库迁移。

但是,当我尝试运行该行时:

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

我收到一个错误: “System.InvalidOperationException:'无法从根提供商解析范围服务'SportsStore.Models.ApplicationDbContext'。'”

我知道这与解决程序范围有关,但我不确定要进行哪些代码更改。

这是完整的文件,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);
            }
        }
    }

如果有任何有用的建议,请告诉我! 谢谢,

问候,

罗伯特

英国伦敦

【问题讨论】:

  • 我认为我的回答 here 应该可以满足您的需求。
  • 好的@Kirk Larkin,所以基于这个答案,我应该在startup.cs的configure方法中添加'IServiceProvider serviceProvider',然后在我的方法中添加以下行:ApplicationDbContext.GetRequiredService(serviceProvider, Configuration) 。等待(); ?

标签: c# asp.net asp.net-mvc asp.net-core


【解决方案1】:

您需要在 Program 类中禁用范围验证:

public class Program {
...

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

【讨论】:

猜你喜欢
  • 2018-04-04
  • 1970-01-01
  • 2020-09-06
  • 2020-08-01
  • 1970-01-01
  • 2020-02-22
  • 2020-05-11
  • 1970-01-01
  • 2020-05-22
相关资源
最近更新 更多