带内存数据库的C#/ OSX

我在Mac上开发基于C#的API,当我尝试按照本教程中的Startup / Configure函数访问DbContext时,.net崩溃:
https://stormpath.com/blog/tutorial-entity-framework-core-in-memory-database-asp-net-core

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddDbContext<ApiContext>(opt => opt.UseInMemoryDatabase());
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        // configure strongly typed settings objects
        var appSettingsSection = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettingsSection);

        // configure jwt authentication
        var appSettings = appSettingsSection.Get<AppSettings>();
        var key = Encoding.ASCII.GetBytes(appSettings.Secret);
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

        // configure DI for application services
        services.AddScoped<IUserService, UserService>();
        services.AddScoped<IClientAccountService, ClientAccountService>();
        services.AddScoped<ISearchService, SearchService>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // global cors policy
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());

        app.UseAuthentication();

        var context = app.ApplicationServices.GetService<ApiContext>();
        AddTestData(context);

        app.UseMvc();
    }

它在第86行失败,它试图从ApplicationServices获取ApiContext:

var context = app.ApplicationServices.GetService< ApiContext>();

使用:未处理的异常:System.InvalidOperationException:无法从根提供程序解析作用域服务“VimvestPro.Data.ApiContext”.

最佳答案 您直接从应用程序容器中解析
scoped service,这是不允许的.如果将ApiContext作为参数添加到Configure方法,它将生成范围并将上下文注入到方法中.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApiContext context)
{
  ...
  AddTestData(context);
  ...
}
点赞