如何解决无法从根提供者解析作用域服务-解决错误?
我正在使用.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",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",Price = 34.95m
},new Product
{
Name = "Stadium",Description = "Flat-packed 35,000-seat stadium",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",Price = 75
},new Product
{
Name = "Bling-Bling King",Description = "Gold-plated,diamond-studded King",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.
}
}
// startup.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();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。