Home | Created on - November 2005
In some cases, you may want to dynamically determine at runtime the appropriate HttpHandler to call for handling a particular request. .NET provides a Factory design pattern that allows you to create a Factory that is responsible for creating the appropriate HttpHandler to deal with the request. This gives you some additional flexibility in creating HttpHandlers. You could look inside an associated file to determine which handler should be called. The Factory pattern also provides a way for you to potentially pre-create a number of handlers and hand them to ASP.NET when it requests one, without the overhead of creating one each and every time. Let's look at below sample, it shows a class that implements IHttpHandlerFactory. This class looks for an argument passed as part of the URL. If the value of this argument is "rama", the ramaHandler is returned to ASP.NET to handle the request. If the value of the argument is "Jeff", the JeffHandler is returned.
using System;
using System.Web;
using System.Web.UI;
namespace Handlers
{
///
/// Summary description for HandlerFactory.
///
public class HandlerFactory : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string requestType,
string url, string pathTranslated)
{
// Check the name property
if(context.Request["Name"] == "rama")
// If it's rama return rama
return new ramaHandler();
else
// Else return Jeff
return new JeffHandler();
}
// required to implement the interface
public void ReleaseHandler(IHttpHandler handler)
{
}
}
/// The ramaHandler
///
public class ramaHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.Write("rama");
}
public bool IsReusable
{
get
{
return true;
}
}
}
/// The JeffHandler
///
public class JeffHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.Write("Jeff");
}
public bool IsReusable
{
get
{
return true;
}
}
}
}
The HttpHandlerFactory is hooked up in Web.Config the same way an ordinary HttpHandler is hooked up.