繁体   English   中英

无法解析ASP.NET Core 2.0中的DbContext

[英]Cannot resolve DbContext in ASP.NET Core 2.0

首先,我试图用示例数据为数据库播种。 我已经读到这是做到这一点的方法(在Startup.Configure中 )(请参阅ASP.NET Core RC2种子数据库

我正在使用带有默认选项的ASP.NET Core 2.0。

和往常一样,我在ConfigureServices注册我的DbContext 但是之后,在Startup.Configure方法中,当我尝试使用GetRequiredService解析它时,它会抛出以下消息:

System.InvalidOperationException:'无法从根提供者解析作用域服务'SGDTP.Infrastructure.Context.SGDTPContext'。

我的启动类是这样的:

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
            //... 
        }
    }
}

我究竟做错了什么? 另外,这是创建种子数据的最佳位置吗?

您正在将SGDTPContext注册为范围服务,然后尝试在范围之外访问它。 要在您的SeedDatabase方法内创建作用域,请使用以下命令:

using (var serviceScope = app.ApplicationServices.CreateScope())
{
    var context = serviceScope.ServiceProvider.GetService<SGDTPContext>();

    // Seed the database.
}

感谢@khellang在注释中指出了CreateScope扩展方法,并感谢@Tseng的注释并回答了如何在EF Core 2中实现播种。

在遵循官方ASP.Net MVC Core 教程时 (在您应向应用程序中添加种子数据的部分中),出现此错误。 长话短说,添加这两行

 using Microsoft.EntityFrameworkCore;
 using Microsoft.Extensions.DependencyInjection;

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
            }
  ...

无法告诉您原因,但这是我遵循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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM