[英]Cannot resolve DbContext in ASP.NET Core 2.0
First of all, I'm trying to seed my database with sample data. 首先,我试图用示例数据为数据库播种。 I have read that this is the way to do it (in Startup.Configure ) (please, see ASP.NET Core RC2 Seed Database ) 我已经读到这是做到这一点的方法(在Startup.Configure中 )(请参阅ASP.NET Core RC2种子数据库 )
I'm using ASP.NET Core 2.0 with the default options. 我正在使用带有默认选项的ASP.NET Core 2.0。
As usual, I register my DbContext
in ConfigureServices
. 和往常一样,我在ConfigureServices
注册我的DbContext
。 But after that, in the Startup.Configure method, when I try to resolve it using GetRequiredService
, it throws with this message: 但是之后,在Startup.Configure方法中,当我尝试使用GetRequiredService
解析它时,它会抛出以下消息:
System.InvalidOperationException: 'Cannot resolve scoped service 'SGDTP.Infrastructure.Context.SGDTPContext' from root provider.' System.InvalidOperationException:'无法从根提供者解析作用域服务'SGDTP.Infrastructure.Context.SGDTPContext'。
My Startup class like this: 我的启动类是这样的:
public abstract class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<SGDTPContext>(options => options.UseInMemoryDatabase("MyDatabase"))
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
SeedDatabase(app);
}
private static void SeedDatabase(IApplicationBuilder app)
{
using (var context = app.ApplicationServices.GetRequiredService<SGDTPContext>())
{
// Seed the Database
//...
}
}
}
What am I doing wrong? 我究竟做错了什么? Also, is this the best place to create seed data? 另外,这是创建种子数据的最佳位置吗?
You're registering SGDTPContext
as a scoped service and then attempting to access it outside of a scope. 您正在将SGDTPContext
注册为范围服务,然后尝试在范围之外访问它。 To create a scope inside your SeedDatabase
method, use the following: 要在您的SeedDatabase
方法内创建作用域,请使用以下命令:
using (var serviceScope = app.ApplicationServices.CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SGDTPContext>();
// Seed the database.
}
Credit to @khellang for pointing out the CreateScope
extension method in the comments and to @Tseng's comment and answer re how to implement seeding in EF Core 2. 感谢@khellang在注释中指出了CreateScope
扩展方法,并感谢@Tseng的注释并回答了如何在EF Core 2中实现播种。
Was getting this error while following the official ASP.Net MVC Core tutorial , in the section where you are supposed to add seeded data to your application. 在遵循官方ASP.Net MVC Core 教程时 (在您应向应用程序中添加种子数据的部分中),出现此错误。 Long story short, adding these two lines 长话短说,添加这两行
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
to the SeedData
class solved it for me: SeedData
类为我解决了这个问题:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
namespace MvcMovie.Models
{
public static class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new MvcMovieContext(
serviceProvider.GetRequiredService<DbContextOptions<MvcMovieContext>>()))
{
// Look for any movies.
if (context.Movie.Any())
{
return; // DB has been seeded
}
...
Can't tell you the WHY, but these were two of the options I got from following the Alt + Enter
quick fix option. 无法告诉您原因,但这是我遵循Alt + Enter
快速修复选项获得的两个选项。
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var key = Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value);
services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")).EnableSensitiveDataLogging());
services.AddMvc();
services.AddTransient<Seed>();
services.AddCors();
services.AddScoped<IAuthRepository, AuthRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(Options =>
{
Options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
}
);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env ,Seed seeder)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
}
});
});
}
seeder.SeedUser();
app.UseCors(x=>x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
app.UseMvc();
}
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.