我正在Mac上开发基于C#的API,并且在尝试按照本教程进行操作的“启动/配置”功能中访问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'。
答案 0 :(得分:1)
您正在直接从应用程序容器中解析scoped service,这是不允许的。如果将ApiContext作为参数添加到Configure方法中,它将生成一个作用域并将上下文注入您的方法中。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApiContext context)
{
...
AddTestData(context);
...
}