和罗恩·米勒一起看这个视频我就明白了https://channel9.msdn.com/Series/Whats-New-with-ASPNET-5/06 https://channel9.msdn.com/Series/Whats-New-with-ASPNET-5/06
(第 22 分钟)将 Entity Framework Core(以前称为 EF7)配置到 ASP.NET Core 1.0 应用程序(以前称为 ASP.NET 5)中的方法Startup.cs
如下:
public void ConfigureServices(IServiceCollection services)
{
//Entity Framework 7 scoped per request??
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<MyDbContext>(options =>
{
options
.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]);
});
//MVC 6
services.AddMvc();
}
然后此 DbContext 将限定为 http 请求因此,只要在整个 http 管道(包括中间件或 MVC)的代码中使用 DbContext,我们就可以确定 DI 容器注入的实例将是相同的。
但问题是它似乎并非如此。在 MVC 的生命周期内,注入的 DbContext 实例确实是相同的,但如下所述:Entity Framework Core 1.0 工作单元与 Asp.Net Core 中间件或 Mvc 过滤器 https://stackoverflow.com/questions/35303617/entity-framework-core-1-0-unit-of-work-with-asp-net-5-with-middleware我试图将以下中间件插入管道,以在控制器完成执行后实现某种集中提交/回滚:
public class UnitOfWorkMiddleware
{
private readonly RequestDelegate _next;
private readonly MyDbContext _dbContext;
private readonly ILogger _logger;
public UnitOfWorkMiddleware(RequestDelegate next, MyDbContext dbContext, ILoggerFactory loggerFactory)
{
_next = next;
_dbContext = dbContext;
_logger = loggerFactory.CreateLogger<UnitOfWorkMiddleware>();
}
public async Task Invoke(HttpContext httpContext)
{
await _next.Invoke(httpContext);
_logger.LogInformation("Saving changes for unit of work if everything went good");
await _dbContext.SaveChangesAsync();
}
}
这个中间件紧接在管道中的 MVC6 之前
//inside Configure(IApplicationBuilder app) in Startup.cs
app.UseMiddleware<UnitOfWorkMiddleware>();
app.UseMvcWithDefaultRoute();
我的中间件中的 DbContext 实例与 MVC 生命周期内注入的实例不同.
这是预期的吗? DbContext 不应该限定在 http 请求范围内吗?有可能实现我想要实现的目标吗?
B 计划是使用MVC 6 全局过滤器(如果我能找到一些有关如何执行此操作的文档)。我假设作为 MVC 6 框架的一部分,注入的 DbContext 实例将是相同的。