使用异步RESTful Web API时要使用的正确Ninject范围是什么

时间:2015-02-17 07:35:03

标签: c# asp.net-mvc asp.net-web-api ninject

在点击刷新页面时(即第二次请求页面),我从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,这是正确的吗?

0 个答案:

没有答案