将继承的 ASP.NET 应用程序移植到使用 SqlCommand 扩展方法实现伪环境事务 ASP.NET 核心:
public static class SqlExtension
{
public static SqlCommand NewCommand( this SqlConnection c )
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = c;
SqlTransaction ambientTransaction = (SqlTransaction)
HttpContext.Current.Items["AmbientTransaction"];
if (ambientTransaction != null)
{
cmd.Transaction = ambientTransaction;
}
return cmd;
}
使用环境事务的 SQL 语句分布在整个代码中的数百个位置。 由于 HttpContext 不再全局可访问,我将不胜感激以下建议:
1(关于如何让事情暂时运作。 是否可以将 HttpContext 注入到扩展方法中?
2(重新实现代码时要遵循的模式,它实现了相同的目标,即将SQL事务包装在单个http请求中完成的所有工作周围。
您有两个选择:
1.直接解决方法中的依赖关系,但我不推荐。虽然你也需要IApplicationBuilder
var httpContext = (IHttpContextAccessor)app.ApplicationServices.GetService(typeof(IHttpContextAccessor))
2.在方法中传递参数
public static SqlCommand NewCommand( this SqlConnection c, IHttpContextAccesor http )
{
}
调用者的依赖,只需在扩展方法中传递 HttpContext 的参数即可。
我在本文中找到了优雅的解决方案。首先,创建静态类 AppContext,然后在"启动"中配置它.cs在"配置"方法中对其进行配置。不要忘记在配置服务方法中添加services.AddHttpContextAccessor();
。