Search code examples
asp.net-mvcdbcontexthttpcontextobjectcontextcontrollercontext

What the heck is a context?


I'm starting to see Contexts everywhere I look. In ASP.NET MVC, there are ControllerContexts, RequestContexts, HttpContexts, FormContexts. In Entity Framework, you have ObjectContexts and DbContexts. Ninject has Ninject.Activation.IContext.

What the heck is a context?


Solution

  • Well, it's kind of a dependency-injection thing, that allows people to say 'Here is the environment you will operate in'. Generally, they provide, unsurprisingly, the "context" for whatever it is. I.e., some state. Perhaps the URL, perhaps some HTTP headers, whatever.

    You are seeing a lot of them because ASP.NET is focused on testing and hence allows these items to be "swapped in", such that you can provide your own context implementations (i.e. define your own state), so that you can run tests appropriately and successfully.

    If you're wondering what state is, well it's just various bits of data that are "given", by the environment. I.e. today it is cold in the office. This is part of the state. But perhaps I want to run my test when it is hot in the office, so I would be able to subclass OfficeContext and return the appropriate state for the appropriate method/etc.