【发布时间】:2022-01-12 10:55:56
【问题描述】:
升级由 70 多个应用程序和 200 多个基类库 (C#) 组成的大型 .NET Framework 4.8 企业应用程序
基类库正在转换为 .NetStandard 2.0,以便它们可供 .NET Framework 和 .NET Core 应用程序使用。然后可以在准备好后完成每个应用程序的迁移。
遇到看似常见但无法找到解决方案的情况
基类库具有静态 HttpContext Request/Response/Session 引用。我知道我可以重构这些依赖项,但这是一项艰巨的工作;
用一个简单的例子;
public class QueryStringHelper : IQueryStringHelper
{
public string GetValue(string key) => HttpContext.Current.Request[key];
}
HttpContext 在 System.Web 中并不存在,需要通过 IHttpContextAccessor 注入。
public class QueryStringHelper : IQueryStringHelper
{
private readonly IHttpContextAccessor _httpContextAccessor;
public QueryStringHelper(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public string GetValue(string key) => _httpContextAccessor.HttpContext.Request[key];
}
在 .NET Core 应用程序中使用这个基类库非常简单,向 DI 容器注册
builder.Services.AddHttpContextAccessor();
但是.. 我们如何在 .NET Framework 应用程序中使用这个基类?这是完全错误的方法,还是有办法做到这一点?
【问题讨论】:
标签: c# .net-core .net-standard httpcontext