Invert constructor / setter using IoC in HttpHandler, is this possible?

I ran into a rather hairy problem. This may be a simple solution, but I cannot find it!

I have a custom HttpHandler that I want to process the request, register certain information, and then enter the data into the database. I use NUnit and Castle Windsor.

So, I have two interfaces; one for registering another for data entry, which is entered by the constructor. I quickly discovered that there was no way to invoke the constructor, because instead of it, the constructor without parameters was always called.

So I thought I would use Setter injection and let Castle Windsor figure it out. This really works when I use container.Resolve<CustomHttpHandler>(); I can check that the logger is not null. (In Application_Start in Global.asax.cs)

The problem is that Castle Windsor can create an instance that the http application isnโ€™t using ???? I think?

Basically, this whole reason was to test the data logger and data repository code in isolation by mocking and unit testing.

Any ideas how I can solve this problem?

Thanks!

+6
dependency-injection ioc-container mocking castle-windsor
source share
2 answers

Impossible, at least not directly. IHttpHandler objects are created using the ASP.NET runtime, and this prevents Windsor from participating in its creation. You can:

  • Tighten dependencies using the container as a service locator.
  • Configure a base handler that creates, injects, and delegates your own handlers (see Spring does this )
  • Use the container as a service locator for another service that processes the entire request (as saret explained )
+2
source

What you can do is force the HttpHandler to call another object that actually processes the request. so in your HttpHandler ProcessRequest method you will do something like this:

 public void ProcessRequest(HttpContext context) { var myHandlerObject = container.Resolve<HandlerObject>(); myHandlerObject.ProcessRequest(context or some state/info that is required) } 
+2
source

All Articles