在点击刷新页面时(即第二次请求页面),我从ObjectDisposedException
控制器操作获得了Index
,我怀疑这是由于我InRequestScope
的使用不正确在Ninject。
这里有一些背景知识,我有一个CustomHttpClient
类包装HttpClient
以向ASP.NET Web API发送GET
个请求:
public class CustomHttpClient : ICustomHttpClient
{
private static readonly HttpMessageHandler HttpMessageHandler =
new HttpClientHandler { UseDefaultCredentials = true };
private readonly HttpClient _httpClient;
private bool _disposed;
public CustomHttpClient(string uriString) : this(new Uri(uriString))
{
}
public CustomHttpClient(Uri baseUri)
{
_httpClient = new HttpClient(HttpMessageHandler) { BaseAddress = baseUri };
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<HttpResponseMessage> GetAsync(string requestUri)
{
return await _httpClient.GetAsync(requestUri);
}
}
我的ASP.NET MVC控制器将此CustomHttpClient
作为依赖项:
public class CustomController : Controller
{
private readonly ICustomHttpClient _customHttpClient;
public CustomController(ICustomHttpClient customHttpClient)
{
_customHttpClient = customHttpClient;
}
public async Task<ActionResult> Index()
{
var response = await _customHttpClient.GetAsync("foo/bar");
// Deserialize the response and return the view
return View();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (_httpClient != null && disposing)
{
_httpClient.Dispose();
}
_dispoed = true;
}
}
My Ninject绑定:
public class CustomNinjectModule : NinjectModule
{
Bind<ICustomHttpClient>()
.To<CustomHttpClient>()
.InRequestScope() // Should I use InCallScope() or InThreadScope() instead?
.WithConstructorArgument(typeof(string), "http://foo.com");
}
我的想法是HttpClient
已在请求结束后处理但async
任务尚未返回HttpResponse
,导致ObjectDisposedException
,这是正确的吗?