我正在 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 方法,它将生成一个范围并将上下文注入(inject)您的方法。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApiContext context)
{
...
AddTestData(context);
...
}
关于带有内存数据库的 C#/OSX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52521175/