HttpContext.Items with ASP.NET MVC

前端 未结 3 2017
独厮守ぢ
独厮守ぢ 2020-12-05 13:28

I\'m implimenting my own ApplicationContext class that uses the singleton pattern. I want to store my instance of it in HttpContext.Items, since it is accessible in all par

3条回答
  •  死守一世寂寞
    2020-12-05 13:52

    Your question is asking a few things but I think item #1 is the answer you're looking for.

    1. Is it fine to use Context.Items for caching on a per request basis? Yes. If in process, per request, per machine in the web farm is your criteria then Context.Items gives you that.

    2. Is Context.Items difficult to test with? As far as testability, I would hide Context.Items behind an interface of some sort. This way you get unit testing capabilities without having to reference Context.Items directly. Otherwise, what do you need to test about Context.Items? That the framework will store and retrieve values? Keep your code ignorant of System.Web and you'll be a happy camper.

    3. Will Context.Items survive RedirectToAction? No. Your test is invalid. It's setting "Hello, world" on every web request and your test spans two web requests. The first is when the Index action is called. The second is when RedirectToAction action is called (it's an HTTP 302). To make it fail, set a new value in the Index action and see if it's retained in the About action.

提交回复
热议问题