Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construtor/Setter Injection using IoC in HttpHandler, is it possible?

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!

like image 953
Id10T-ERROR Avatar asked Aug 19 '10 05:08

Id10T-ERROR


2 Answers

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)
like image 78
Mauricio Scheffer Avatar answered Jan 03 '23 16:01

Mauricio Scheffer


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)
}
like image 45
saret Avatar answered Jan 03 '23 16:01

saret