I have several dependency injection services which are dependent on stuff like HTTP context. Right now I'm configuring them as singletons the Windsor container in the Application_Start handler, which is obviously a problem for such services.
What is the best way to handle this? I'm considering making them transient and then releasing them after each HTTP request. But what is the best way/place to inject the HTTP context into them? Controller factory or somewhere else?
The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System. Web.
ASP.NET MVC is no longer in active development. The last version update was in November 2018. Despite this, a lot of projects are using ASP.NET MVC for web solution development. As to JetBrains' research, 42% of software developers were using the framework in 2020.
Asp.Net MVC is a lightweight and follows MVC (Model, View, Controller) pattern based development, model. Asp.Net Web Form has server controls. Asp.Net MVC has HTML helpers. Asp.Net Web Form supports view state for state management at the client side.
It's really difficult to try and learn an entirely new language/framework under pressure. If you're required to deliver working software for your day job, trying to learn ASP.NET Core at the same time might be heaping too much pressure on yourself.
Just like Mark said, you need to register these http-dependent services either as PerWebRequest or Transient. Here's a sample that shows how to register and inject a HttpRequest or HttpContext:
public class Service {
private readonly HttpRequestBase request;
public Service(HttpRequestBase request) {
this.request = request;
}
public string RawUrl {
get {
return request.RawUrl;
}
}
}
...
protected void Application_Start(object sender, EventArgs e) {
IWindsorContainer container = new WindsorContainer();
container.AddFacility<FactorySupportFacility>();
container.AddComponentLifeStyle<Service>(LifestyleType.Transient);
container.Register(Component.For<HttpRequestBase>()
.LifeStyle.PerWebRequest
.UsingFactoryMethod(() => new HttpRequestWrapper(HttpContext.Current.Request)));
container.Register(Component.For<HttpContextBase>()
.LifeStyle.PerWebRequest
.UsingFactoryMethod(() => new HttpContextWrapper(HttpContext.Current)));
}
By using HttpRequestBase
instead of HttpRequest
you can easily mock it out for testing.
Also, don't forget to register PerWebRequestLifestyleModule
in your web.config.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With