HTTPHandler and IsReusable with WebHandler

I have a problem with reusable HTTPHandlers. I wanted to check how the IsReusable property IsReusable . Therefore, I created two handlers:

Reusable:

 public class ReusableHandler : IHttpHandler { public bool IsReusable { get { return true; } } private int _counter; public ReusableHandler() { _counter = 0; } public void ProcessRequest(HttpContext context) { context.Response.Write("Reusable: " + _counter++); } } 

And cannot be reused:

 public class NonReusableHandler : IHttpHandler { public bool IsReusable { get { return false; } } private int _counter; public NonReusableHandler() { _counter = 0; } public void ProcessRequest(HttpContext context) { context.Response.Write("NonReusable: " + _counter++); } } 

Both of them work as expected: each time the return value is returned, it increases, and NonReusable returns 0 each time. But when I use my handlers as WebHandlers (* .ashx), they both return 0 every time (the code is exactly the same). Does this mean that when I use WebHandlers, the IsReusable property IsReusable ignored?

+6
source share
1 answer

The default .NET configuration should use the System.Web.UI.SimpleHandlerFactory type to process requests for *.ashx . You can verify this by looking at the Http handler section in IIS Manager.

If you look at the source code for this factory, you will see that it does not check the IsReusable property at IsReusable . It is also stateless - it does not cache instantiated instances. To see the factory class that uses this property instead, see System.Web.Configuration.HandlerFactoryWrapper .

Now, if you look at System.Web.HttpApplication.RecycleHandlers() , you see that it indirectly calls the System.Web.IHttpHandlerFactory.ReleaseHandler() method (the factory cache mentioned in the next paragraph does not by itself cache the instance instance of the handler ) The application itself ignores the IsReusable property (it is assumed that it will be a factory) and, as was discovered earlier, a factory is used in the .ashx files, which will not reuse instances.

It's also worth noting that System.Web.HttpApplication.GetFactory() seems to use a cache, but this cache will only store an instance of the factory itself (if one is specified). If no explicit factory is specified, the method will create the HandlerFactoryWrapper mentioned above (which in turn will cache instances of the handler).

As far as I can see, there is no factory class in the .NET framework that can be used instead of SimpleHandlerFactory ( HandlerFactoryWrapper does not have a constructor without parameters), although you can create your own.

+2
source

Source: https://habr.com/ru/post/915613/


All Articles