'Why is the HttpContextHolder needed when implementing the HttpContextAccessor based on AsyncLocal?

I don't understand why they use HttpContextHolder as in this code for HttpContextAccessor.HttpContext:

public HttpContext? HttpContext
{
    get
    {
        return _httpContextCurrent.Value?.Context;
    }
    set
    {
        var holder = _httpContextCurrent.Value;
        if (holder != null)
        {
            // Clear current HttpContext trapped in the AsyncLocals, as its done.
            holder.Context = null;
        }

        if (value != null)
        {
            // Use an object indirection to hold the HttpContext in the AsyncLocal,
            // so it can be cleared in all ExecutionContexts when its cleared.
            _httpContextCurrent.Value = new HttpContextHolder { Context = value };
        }
    }
}

Why can't we use it in a simpler way like this?

public HttpContext? HttpContext
{
    get
    {
        //the Value references an instance of HttpContext directly
        //instead of via a holder
        return _httpContextCurrent.Value;
    }
    set
    {
        _httpContextCurrent.Value = value;            
    }
}

Is there any memory-leak issue involved in here affecting how we code it?

PS: the full source code for HttpContextAccessor



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source