Creating STA COM compatible ASP.NET Applications

Posted by Rick Strahl on West-Wind See other posts from West-Wind or by Rick Strahl
Published on Wed, 19 Sep 2012 01:36:42 GMT Indexed on 2012/09/19 3:38 UTC
Read the original article Hit count: 950

Filed under:
|
|
|

When building ASP.NET applications that interface with old school COM objects like those created with VB6 or Visual FoxPro (MTDLL), it's extremely important that the threads that are serving requests use Single Threaded Apartment Threading. STA is a COM built-in technology that allows essentially single threaded components to operate reliably in a multi-threaded environment. STA's guarantee that COM objects instantiated on a specific thread stay on that specific thread and any access to a COM object from another thread automatically marshals that thread to the STA thread. The end effect is that you can have multiple threads, but a COM object instance lives on a fixed never changing thread.

ASP.NET by default uses MTA (multi-threaded apartment) threads which are truly free spinning threads that pay no heed to COM object marshaling. This is vastly more efficient than STA threading which has a bit of overhead in determining whether it's OK to run code on a given thread or whether some sort of thread/COM marshaling needs to occur. MTA COM components can be very efficient, but STA COM components in a multi-threaded environment always tend to have a fair amount of overhead.

It's amazing how much COM Interop I still see today so while it seems really old school to be talking about this topic, it's actually quite apropos for me as I have many customers using legacy COM systems that need to interface with other .NET applications. In this post I'm consolidating some of the hacks I've used to integrate with various ASP.NET technologies when using STA COM Components.

STA in ASP.NET

Support for STA threading in the ASP.NET framework is fairly limited. Specifically only the original ASP.NET WebForms technology supports STA threading directly via its STA Page Handler implementation or what you might know as ASPCOMPAT mode. For WebForms running STA components is as easy as specifying the ASPCOMPAT attribute in the @Page tag:

<%@ Page Language="C#" AspCompat="true" %>

which runs the page in STA mode. Removing it runs in MTA mode. Simple.

Unfortunately all other ASP.NET technologies built on top of the core ASP.NET engine do not support STA natively. So if you want to use STA COM components in MVC or with class ASMX Web Services, there's no automatic way like the ASPCOMPAT keyword available.

So what happens when you run an STA COM component in an MTA application? In low volume environments - nothing much will happen. The COM objects will appear to work just fine as there are no simultaneous thread interactions and the COM component will happily run on a single thread or multiple single threads one at a time. So for testing running components in MTA environments may appear to work just fine.

However as load increases and threads get re-used by ASP.NET COM objects will end up getting created on multiple different threads. This can result in crashes or hangs, or data corruption in the STA components which store their state in thread local storage on the STA thread. If threads overlap this global store can easily get corrupted which in turn causes problems. STA ensures that any COM object instance loaded always stays on the same thread it was instantiated on.

What about COM+?

COM+ is supposed to address the problem of STA in MTA applications by providing an abstraction with it's own thread pool manager for COM objects. It steps in to the COM instantiation pipeline and hands out COM instances from its own internally maintained STA Thread pool. This guarantees that the COM instantiation threads are STA threads if using STA components.

COM+ works, but in my experience the technology is very, very slow for STA components. It adds a ton of overhead and reduces COM performance noticably in load tests in IIS. COM+ can make sense in some situations but for Web apps with STA components it falls short. In addition there's also the need to ensure that COM+ is set up and configured on the target machine and the fact that components have to be registered in COM+. COM+ also keeps components up at all times, so if a component needs to be replaced the COM+ package needs to be unloaded (same is true for IIS hosted components but it's more common to manage that).

COM+ is an option for well established components, but native STA support tends to provide better performance and more consistent usability, IMHO.

STA for non supporting ASP.NET Technologies

As mentioned above only WebForms supports STA natively. However, by utilizing the WebForms ASP.NET Page handler internally it's actually possible to trick various other ASP.NET technologies and let them work with STA components. This is ugly but I've used each of these in various applications and I've had minimal problems making them work with FoxPro STA COM components which is about as dififcult as it gets for COM Interop in .NET.

In this post I summarize several STA workarounds that enable you to use STA threading with these ASP.NET Technologies:

  • ASMX Web Services
  • ASP.NET MVC
  • WCF Web Services
  • ASP.NET Web API

ASMX Web Services

I start with classic ASP.NET ASMX Web Services because it's the easiest mechanism that allows for STA modification. It also clearly demonstrates how the WebForms STA Page Handler is the key technology to enable the various other solutions to create STA components.

Essentially the way this works is to override the WebForms Page class and hijack it's init functionality for processing requests. Here's what this looks like for Web Services:

namespace FoxProAspNet
{
    public class WebServiceStaHandler :
        System.Web.UI.Page, IHttpAsyncHandler
    {

        protected override void OnInit(EventArgs e)
        {
            IHttpHandler handler =
                new WebServiceHandlerFactory().GetHandler(
                    this.Context,
                    this.Context.Request.HttpMethod,
                    this.Context.Request.FilePath,
                    this.Context.Request.PhysicalPath);
            handler.ProcessRequest(this.Context);

            this.Context.ApplicationInstance.CompleteRequest();
        }


        public IAsyncResult BeginProcessRequest(
            HttpContext context, AsyncCallback cb, object extraData)
        {
            return this.AspCompatBeginProcessRequest(context, cb, extraData);
        }


        public void EndProcessRequest(IAsyncResult result)
        {
            this.AspCompatEndProcessRequest(result);
        }
    }

    public class AspCompatWebServiceStaHandlerWithSessionState :
                 WebServiceStaHandler, IRequiresSessionState
    {
    }

}

This class overrides the ASP.NET WebForms Page class which has a little known AspCompatBeginProcessRequest() and AspCompatEndProcessRequest() method that is responsible for providing the WebForms ASPCOMPAT functionality. These methods handle routing requests to STA threads. Note there are two classes - one that includes session state and one that does not. If you plan on using ASP.NET Session state use the latter class, otherwise stick to the former. This maps to the EnableSessionState page setting in WebForms.

This class simply hooks into this functionality by overriding the BeginProcessRequest and EndProcessRequest methods and always forcing it into the AspCompat methods.

The way this works is that BeginProcessRequest() fires first to set up the threads and starts intializing the handler. As part of that process the OnInit() method is fired which is now already running on an STA thread. The code then creates an instance of the actual WebService handler factory and calls its ProcessRequest method to start executing which generates the Web Service result. Immediately after ProcessRequest the request is stopped with Application.CompletRequest() which ensures that the rest of the Page handler logic doesn't fire. This means that even though the fairly heavy Page class is overridden here, it doesn't end up executing any of its internal processing which makes this code fairly efficient.

In a nutshell, we're highjacking the Page HttpHandler and forcing it to process the WebService process handler in the context of the AspCompat handler behavior.

Hooking up the Handler

Because the above is an HttpHandler implementation you need to hook up the custom handler and replace the standard ASMX handler. To do this you need to modify the web.config file (here for IIS 7 and IIS Express):

 <configuration>
   <system.webServer>
    <handlers>
      <remove name="WebServiceHandlerFactory-Integrated-4.0" />      
      <add name="Asmx STA Web Service Handler" path="*.asmx" verb="*" 
type="FoxProAspNet.WebServiceStaHandler" precondition="integrated"/> </handlers> </system.webServer> </configuration>

(Note: The name for the WebServiceHandlerFactory-Integrated-4.0 might be slightly different depending on your server version. Check the IIS Handler configuration in the IIS Management Console for the exact name or simply remove the handler from the list there which will propagate to your web.config).

For IIS 5 & 6 (Windows XP/2003) or the Visual Studio Web Server use:

<configuration>
<system.web>
<httpHandlers> <remove path="*.asmx" verb="*" /> <add path="*.asmx" verb="*" type="FoxProAspNet.WebServiceStaHandler" /> </httpHandlers> </system.web>
</configuration>

To test, create a new ASMX Web Service and create a method like this:

    [WebService(Namespace = "http://foxaspnet.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class FoxWebService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World. Threading mode is: " + 
System.Threading.
Thread.CurrentThread.GetApartmentState(); } }

Run this before you put in the web.config configuration changes and you should get:

Hello World. Threading mode is: MTA

Then put the handler mapping into Web.config and you should see:

Hello World. Threading mode is: STA

And you're on your way to using STA COM components. It's a hack but it works well! I've used this with several high volume Web Service installations with various customers and it's been fast and reliable.

ASP.NET MVC

ASP.NET MVC has quickly become the most popular ASP.NET technology, replacing WebForms for creating HTML output. MVC is more complex to get started with, but once you understand the basic structure of how requests flow through the MVC pipeline it's easy to use and amazingly flexible in manipulating HTML requests. In addition, MVC has great support for non-HTML output sources like JSON and XML, making it an excellent choice for AJAX requests without any additional tools.

Unlike WebForms ASP.NET MVC doesn't support STA threads natively and so some trickery is needed to make it work with STA threads as well.

MVC gets its handler implementation through custom route handlers using ASP.NET's built in routing semantics. To work in an STA handler requires working in the Page Handler as part of the Route Handler implementation.

As with the Web Service handler the first step is to create a custom HttpHandler that can instantiate an MVC request pipeline properly:

public class MvcStaThreadHttpAsyncHandler : Page, IHttpAsyncHandler, IRequiresSessionState
{
    private RequestContext _requestContext;
    public MvcStaThreadHttpAsyncHandler(RequestContext requestContext)
    {
        if (requestContext == null)
            throw new ArgumentNullException("requestContext");

        _requestContext = requestContext;
    }

    public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
    {
        return this.AspCompatBeginProcessRequest(context, cb, extraData);
    }

    protected override void OnInit(EventArgs e)
    {
        var controllerName = _requestContext.RouteData.GetRequiredString("controller");
        var controllerFactory = ControllerBuilder.Current.GetControllerFactory();
        var controller = controllerFactory.CreateController(_requestContext, controllerName);
        if (controller == null)
            throw new InvalidOperationException("Could not find controller: " + controllerName);
        try
        {
            controller.Execute(_requestContext);
        }
        finally
        {
            controllerFactory.ReleaseController(controller);
        }
        this.Context.ApplicationInstance.CompleteRequest();
    }

    public void EndProcessRequest(IAsyncResult result)
    {
        this.AspCompatEndProcessRequest(result);
    }

    public override void ProcessRequest(HttpContext httpContext)
    {
        throw new NotSupportedException("STAThreadRouteHandler does not support ProcessRequest called (only BeginProcessRequest)");
    }
}

This handler code figures out which controller to load and then executes the controller. MVC internally provides the information needed to route to the appropriate method and pass the right parameters. Like the Web Service handler the logic occurs in the OnInit() and performs all the processing in that part of the request.

Next, we need a RouteHandler that can actually pick up this handler. Unlike the Web Service handler where we simply registered the handler, MVC requires a RouteHandler to pick up the handler. RouteHandlers look at the URL's path and based on that decide on what handler to invoke.

The route handler is pretty simple - all it does is load our custom handler:

    public class MvcStaThreadRouteHandler : IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            if (requestContext == null)
                throw new ArgumentNullException("requestContext");

            return new MvcStaThreadHttpAsyncHandler(requestContext);
        }
    }

At this point you can instantiate this route handler and force STA requests to MVC by specifying a route. The following sets up the ASP.NET Default Route:

Route mvcRoute = new Route("{controller}/{action}/{id}",
                            new RouteValueDictionary( new { 
                                    controller = "Home", 
                                    action = "Index", 
                                    id = UrlParameter.Optional 
                                }),
                            new MvcStaThreadRouteHandler());
RouteTable.Routes.Add(mvcRoute);

 

To make this code a little easier to work with and mimic the behavior of the routes.MapRoute() functionality extension method that MVC provides, here is an extension method for MapMvcStaRoute():

    public static class RouteCollectionExtensions
    {

        public static void MapMvcStaRoute(this RouteCollection routeTable,
                                     string name,
                                     string url,
                                     object defaults = null)
        {
            Route mvcRoute = new Route(url,
                                       new RouteValueDictionary(defaults),
                                       new MvcStaThreadRouteHandler());
            RouteTable.Routes.Add(mvcRoute);
        }
    }

With this the syntax to add  route becomes a little easier and matches the MapRoute() method:

RouteTable.Routes.MapMvcStaRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

The nice thing about this route handler, STA Handler and extension method is that it's fully self contained. You can put all three into a single class file and stick it into your Web app, and then simply call MapMvcStaRoute() and it just works. Easy!

To see whether this works create an MVC controller like this:

    public class ThreadTestController : Controller
    {        
        public string ThreadingMode()
        {
            return Thread.CurrentThread.GetApartmentState().ToString();
        }
    }

Try this test both with only the MapRoute() hookup in the RouteConfiguration in which case you should get MTA as the value. Then change the MapRoute() call to MapMvcStaRoute() leaving all the parameters the same and re-run the request. You now should see STA as the result.

You're on your way using STA COM components reliably in ASP.NET MVC.

WCF Web Services running through IIS

WCF Web Services provide a more robust and wider range of services for Web Services. You can use WCF over HTTP, TCP, and Pipes, and WCF services support WS* secure services. There are many features in WCF that go way beyond what ASMX can do. But it's also a bit more complex than ASMX. As a basic rule if you need to serve straight SOAP Services over HTTP I 'd recommend sticking with the simpler ASMX services especially if COM is involved. If you need WS* support or want to serve data over non-HTTP protocols then WCF makes more sense.

WCF is not my forte but I found a solution from Scott Seely on his blog that describes the progress and that seems to work well. I'm copying his code below so this STA information is all in one place and quickly explain.

Scott's code basically works by creating a custom OperationBehavior which can be specified via an [STAOperation] attribute on every method. Using his attribute you end up with a class (or Interface if you separate the contract and class) that looks like this:

    [ServiceContract]
    public class WcfService
    {
        [OperationContract]
        public string HelloWorldMta()
        {
            return Thread.CurrentThread.GetApartmentState().ToString();
        }

        // Make sure you use this custom STAOperationBehavior
        // attribute to force STA operation of service methods
        [STAOperationBehavior]
        [OperationContract]
        public string HelloWorldSta()
        {
            return Thread.CurrentThread.GetApartmentState().ToString();
        }

    } 

Pretty straight forward. The latter method returns STA while the former returns MTA. To make STA work every method needs to be marked up.

The implementation consists of the attribute and OperationInvoker implementation. Here are the two classes required to make this work from Scott's post:

public class STAOperationBehaviorAttribute : Attribute, IOperationBehavior
{
    public void AddBindingParameters(OperationDescription operationDescription,
        System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(OperationDescription operationDescription,
        System.ServiceModel.Dispatcher.ClientOperation clientOperation)
    {
        // If this is applied on the client, well, it just doesn’t make sense.
        // Don’t throw in case this attribute was applied on the contract
        // instead of the implementation.
    }

    public void ApplyDispatchBehavior(OperationDescription operationDescription,
        System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
    {
        // Change the IOperationInvoker for this operation.
        dispatchOperation.Invoker = new STAOperationInvoker(dispatchOperation.Invoker);
    }

    public void Validate(OperationDescription operationDescription)
    {
        if (operationDescription.SyncMethod == null)
        {
            throw new InvalidOperationException("The STAOperationBehaviorAttribute " +
                "only works for synchronous method invocations.");
        }
    }
}

public class STAOperationInvoker : IOperationInvoker
{
    IOperationInvoker _innerInvoker;
    public STAOperationInvoker(IOperationInvoker invoker)
    {
        _innerInvoker = invoker;
    }

    public object[] AllocateInputs()
    {
        return _innerInvoker.AllocateInputs();
    }

    public object Invoke(object instance, object[] inputs, out object[] outputs)
    {
        // Create a new, STA thread
        object[] staOutputs = null;
        object retval = null;
        Thread thread = new Thread(
            delegate()
            {
                retval = _innerInvoker.Invoke(instance, inputs, out staOutputs);
            });
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
        outputs = staOutputs;
        return retval;
    }

    public IAsyncResult InvokeBegin(object instance, object[] inputs,
        AsyncCallback callback, object state)
    {
        // We don’t handle async…
        throw new NotImplementedException();
    }

    public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
    {
        // We don’t handle async…
        throw new NotImplementedException();
    }

    public bool IsSynchronous
    {
        get { return true; }
    }
}

The key in this setup is the Invoker and the Invoke method which creates a new thread and then fires the request on this new thread.

Because this approach creates a new thread for every request it's not super efficient. There's a bunch of overhead involved in creating the thread and throwing it away after each thread, but it'll work for low volume requests and insure each thread runs in STA mode. If better performance is required it would be useful to create a custom thread manager that can pool a number of STA threads and hand off threads as needed rather than creating new threads on every request.

If your Web Service needs are simple and you need only to serve standard SOAP 1.x requests, I would recommend sticking with ASMX services. It's easier to set up and work with and for STA component use it'll be significantly better performing since ASP.NET manages the STA thread pool for you rather than firing new threads for each request. One nice thing about Scotts code is though that it works in any WCF environment including self hosting. It has no dependency on ASP.NET or WebForms for that matter.

STA - If you must

STA components are a  pain in the ass and thankfully there isn't too much stuff out there anymore that requires it. But when you need it and you need to access STA functionality from .NET at least there are a few options available to make it happen. Each of these solutions is a bit hacky, but they work - I've used all of them in production with good results with FoxPro components.

I hope compiling all of these in one place here makes it STA consumption a little bit easier. I feel your pain :-)

Resources

© Rick Strahl, West Wind Technologies, 2005-2012
Posted in FoxPro   ASP.NET  .NET  COM  

© West-Wind or respective owner

Related posts about foxpro

Related posts about ASP.NET