views:

85

answers:

2

Hi. I've ran into a rather hairy problem. There is probably a simple solution to this but I can't find it!

I have a custom HttpHandler that I want to process a request, log certain info then enter the details in the database. I'm using NUnit and Castle Windsor.

So I have two interfaces; one for logging the other for data entry, which are constructor injected. I quickly found out that there is no way to call the constructor as the default parameterless constructor is always called instead.

So I thought I would use Setter injection and let Castle windsor sort it out. This actually works as 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 although Castle Windsor can create the instance the http application is not using it??? I think??

Basically the whole reason for doing it this way was to be able to test the logger and data repository code in isolation via mocking and unit testing.

Any ideas how I can go about solving this problem?

Thanks!

+1  A: 

What you could do is have the HttpHandler call out to another object that actually handles the request. so in your HttpHandler's ProcessRequest method you would do something like this:

public void ProcessRequest(HttpContext context)
{
 var myHandlerObject = container.Resolve<HandlerObject>();
 myHandlerObject.ProcessRequest(context or some state/info that is required)
}
saret
Hi. Thanks for the idea. It could be the solution, one of the other options Mauricio. Thanks!
Matt
A: 

Not possible, at least not directly. IHttpHandler objects are instantiated by the ASP.NET runtime and it doesn't allow Windsor to get involved in its creation. You can either:

  • Pull dependencies, by using the container as a service locator.
  • Set up a base handler that creates, injects and delegates to your own handlers (see how Spring does it)
  • Use the container as a service locator for another service that handles the entire request (as saret explained)
Mauricio Scheffer
Dang, I had a feeling it might be the case. Could you explain a little your first point: Pull dependencies, by using the container as a service locator.? Thanks!
Matt
@Matt: from your HttpHandler, call the container to fetch whatever dependencies you need.
Mauricio Scheffer
Thanks for the reply Mauricio. Understood!
Matt
Hi Mauricio. I have updated my post, would be great if you could take a look when you have time. Thanks!
Matt