【发布时间】:2017-08-16 19:34:11
【问题描述】:
我想知道在启动类中使用依赖项的正确方法是什么?
我已经配置了我的应用程序并在服务中添加了一个上下文
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework().AddDbContext<ApplicationContext>(options =>
options.UseSqlServer(connection));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "https://localhost:4430",
RequireHttpsMetadata = false,
ApiName = "api",
JwtBearerEvents = new SyncUserBearerEvent()
{
OnTokenValidated = async tokenValidationContext =>
{
var claimsIdentity = tokenValidationContext.Ticket.Principal.Identity as ClaimsIdentity;
if (claimsIdentity != null)
{
// Get the user's ID
string userId = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "sub").Value;
}
//I need to spawn a context here
}
}
}
});
}
我需要在接下来调用的 configure 方法中使用这个上下文。我读过一些创建新 DbContext 的文章,但不正确,应该从我们的服务中使用。
在启动方法中使用新的 Db 上下文的正确方法是什么?
【问题讨论】:
标签: c# entity-framework dependency-injection asp.net-core