Releasing http scoped objects when using OpenRasta with StructureMap

StructureMap isn’t quite as pro-active as Castle Windsor when it comes to releasing (and disposing) of http scoped objects. So it’s generally a good practice to do so explicitly at the end of a web request:

protected void Application_EndRequest(object sender, EventArgs e)
{
    ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}

My first attempt to reproduce this with OpenRasta used a pipeline contributor:

using OpenRasta.Pipeline;
using OpenRasta.Web;
using StructureMap.Pipeline;

namespace OpenRasta.DI.StructureMap.Pipeline.Contributors
{
	public class ReleaseAndDisposeAllHttpScopedObjects : IPipelineContributor
	{
		public void Initialize(IPipeline pipelineRunner)
		{
			pipelineRunner.Notify(ReleaseAndDispose)
				.After<KnownStages.IOperationExecution>()
				.And.Before<KnownStages.IOperationResultInvocation>();
		}

		private static PipelineContinuation ReleaseAndDispose(ICommunicationContext communicationContext)
		{
			HttpContextLifecycle.DisposeAndClearAll();
			return PipelineContinuation.Continue;
		}
	}
}

Thankfully, Seb pointed out that it made more sense to hook into IDependencyResolver.HandleIncomingRequestProcessed():

public void HandleIncomingRequestProcessed()
{
    HttpContextLifecycle.DisposeAndClearAll();
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s