我们的 MVC 应用程序使用 HttpClient 调用 WebAPI 操作。我决定使用 StructureMap 注入 HttpClient 并在控制器中覆盖 dispose
public HomeController(HttpClient httpClient)
{
_httpClient = httpClient;
}
protected override void Dispose(bool disposing)
{
if (disposing && _httpClient != null)
{
_httpClient.Dispose();
}
base.Dispose(disposing);
}
StructureMap ObjectInitialize 基本上看起来像这样..
x.For<HttpClient>().Use(() => new HttpClient() { BaseAddress = "my/uri/"});
当我构建它时,CodeAnalysis 会抱怨"Dispose objects before losing scope"
并指向 IoC 代码。
我可以抑制它吗,或者我需要在哪里处理 HttpClient?我也试过
protected void Application_EndRequest(object sender, EventArgs e)
{
ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}
但是我仍然违反了规则。