What is the purpose of injecting an HttpContextBase into a controller with IoC

I saw a lot of code samples using the IoC container with registrations, such as:

// Autofac builder.Register(c => new HttpContextWrapper(HttpContext.Current)) .As<HttpContextBase>() .InstancePerRequest(); // Again Autofac builder.RegisterModule(new AutofacWebTypesModule()); 

(see src for AutofacWebTypesModule HERE )

 // Castle Windsor container.Register(Component.For<HttpContextBase() .LifeStyle.PerWebRequest .UsingFactoryMethod(() => new HttpContextWrapper(HttpContext.Current))); 

Together with controllers using constructor injection:

 public class HomeController : Controller { private readonly HttpContextBase _httpContext; public HomeController(HttpContextBase httpContext) { _httpContext = httpContext; } //.... } 

Question 1:

Could you explain the reason for migrating HttpContextBase, HttpRequestBase, etc.?

Question 2:

What would be the difference between the Introduced HttpContextBase vs HttpContext (Controller property) vs System.Web.HttpContext.Current

Update

Question 3:

Which HttpContext to use in the code entered by One or is it also good to call it through HttpContext and System.Web.HttpContext.Current ? Are there any problems when calling in both directions?

+5
source share
1 answer

Answer 1

HttpContext is a notorious pain when it comes to testing, as it only exists in the context of the request. Since .net 3.5 HttpContextBase is an abstraction of HttpContext and lends itself to implementation through the IOC framework

By allowing the IOC container to handle it, you can register another / deterministic instance that will be injected into your components during testing. In regular code, you enter HttpContextWrapper , which is the default implementation

On the linked page:

The HttpContextBase class is an abstract class that contains the same as the HttpContext class. The HttpContextBase class allows you to create derived classes similar to the HttpContext class, but which you can configure and work outside of the ASP.NET pipeline. When performing unit testing, a derived class is usually used to implement participants with custom behavior that matches the scenario you are testing.

Answer 2

Entered HttpContextBase returns the data necessary for successful completion of the test: a specific query string, a specific query, etc. Typically, an implemented implementation will contain only the necessary methods for the test, ignoring all others, for example, the context .User.Identity.Name property for authentication.

Answer 3

In your code, you should always use the introduced HttpContextBase , since you do not want to depend on a specific implementation, which may not work during testing. If you call both methods, you may run into problems, especially in tests, since HttpContext.Current returns null.

+4
source

Source: https://habr.com/ru/post/1202978/


All Articles