NLog.Web icon indicating copy to clipboard operation
NLog.Web copied to clipboard

Skip allocating new HttpContextWrapper for every LayoutRenderer

Open snakefoot opened this issue 3 years ago • 2 comments

It is silly that we have this code:

    public class DefaultHttpContextAccessor : IHttpContextAccessor
    {
        public HttpContextBase HttpContext
        {
            get
            {
                var httpContext = System.Web.HttpContext.Current;
                if (httpContext == null)
                    return null;
                return new HttpContextWrapper(httpContext); // Unnecessary allocation
            }
        }
    }

Would be better just using System.Web.HttpContext-instance directly, since allocation of HttpContextWrapper does not seem to provide any value (Since there is TestInvolvingAspNetHttpContext)

snakefoot avatar May 29 '22 17:05 snakefoot

I attempted this, had many build errors, once those were resolved many unit tests fail since NSubstitute will not work on HttpContext, the methods are not virtual. Since HttpContextBase or HttpContextWrapper is not an HttpContext I am pondering how to leave NLog.Web using HttpContext directly but have NLog.Web.Tests use HttpContextBase, have not reached an answer yet.

bakgerman avatar Aug 13 '23 14:08 bakgerman

Maybe just a manual mock like this:

        HttpContext httpContext = new HttpContext(new MyWorkerRequest());

        public class MyWorkerRequest : SimpleWorkerRequest
        {
            public MyWorkerRequest()
                :base("/", "/", "/", "", new StringWriter(CultureInfo.InvariantCulture))
            {
            }

            public override bool IsEntireEntityBodyIsPreloaded() => true;
            public override byte[] GetPreloadedEntityBody() => Array.Empty<byte>();
        }

snakefoot avatar Aug 13 '23 14:08 snakefoot