An handler factory is the class that implements IHttpHandlerFactory and is responsible for instantiating an handler (IHttpHandler) that will process the current request. This is true for all kinds of web requests, whether they are for ASPX pages, ASMX/SVC web services, ASHX/AXD handlers, or any other kind of file. Also used for restricting access for certain file types, such as Config, Csproj, etc.
Handler factories are registered on the global Web.config file, normally located at %WINDIR%\Microsoft.NET\Framework<x64>\vXXXX\Config for a given path and request type (GET, POST, HEAD, etc). This goes on section <httpHandlers>.
You would create a custom handler factory for a number of reasons, let me list just two:
- A centralized place for using dependency injection;
- Also a centralized place for invoking custom methods or performing some kind of validation on all pages.
Let’s see an example using Unity for injecting dependencies into a page, suppose we have this on Global.asax.cs:
We instantiate Unity and register a concrete implementation for an interface, this could/should probably go in the Web.config file. Forget about its actual definition, it’s not important.
Then, we create a custom handler factory:
It inherits from PageHandlerFactory, which is .NET’s included factory for building regular ASPX pages. We override the GetHandler method and issue a call to the BuildUp method, which will inject required dependencies, if any exist.
An example page with dependencies might be:
Notice the DependencyAttribute, it is used by Unity to identify properties that require dependency injection. When BuildUp is called, the Functionality property (or any other properties with the DependencyAttribute attribute) will receive the concrete implementation associated with it’s type, as registered on Unity.
Another example, checking a page for authorization. Let’s define an interface first:
An a page implementing that interface:
For this, we would use an handler factory such as this:
The UnauthorizedHandler is an example of an IHttpHandler that merely returns an error code to the client, but does not cause redirection to the login page, it is included merely as an example.
One thing we must keep in mind is, there can be only one handler factory registered for a given path/request type (verb) tuple. A typical registration would be:
First we remove the previous registration for ASPX files, and then we register our own.
And that’s it. A very useful mechanism which I use lots of times.