For*_*man 5 c# dbcontext entity-framework-core
我正在 Mac 上开发基于 C# 的 API,当我尝试按照本教程在启动/配置功能中访问 DbContext 时,.net 崩溃: https: //stormpath.com/blog/tutorial-entity-framework-core-in -内存数据库-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();
}
Run Code Online (Sandbox Code Playgroud)
它在第 86 行失败,尝试从 ApplicationServices 获取 ApiContext:
var context = app.ApplicationServices.GetService<ApiContext>();
包含:未处理的异常:System.InvalidOperationException:无法从根提供程序解析作用域服务“VimvestPro.Data.ApiContext”。
您直接从应用程序容器解析范围服务,这是不允许的。如果将 ApiContext 作为参数添加到Configure 方法中,它将生成一个作用域并将上下文注入到您的方法中。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApiContext context)
{
...
AddTestData(context);
...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
372 次 |
最近记录: |