StructureMap integration and ReleaseInstance

Topics: Web Api
Oct 19, 2011 at 3:27 AM

I'm trying to use StructureMap in WebApiConfiguration to create and release the services. Everything is going fine except I don't know what is the correct way to release the created service. My code is based on the ContactsApi sample.

 

Here's my WebApiConfiguration and standard StructureMap registry. StructureMap is initialized in Application_Start.

public class CustomConfiguration : WebApiConfiguration
{
	public CustomConfiguration()
	{
		this.CreateInstance = this.OnCreateInstance;
		this.ReleaseInstance = this.OnReleaseInstance;
	}

	private void OnReleaseInstance(InstanceContext instanceContext, object instance)
	{
		Debug.WriteLine("Releasing all http context scoped objects");
		ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
	}

	private object OnCreateInstance(Type type, InstanceContext context, HttpRequestMessage message)
	{
		Debug.WriteLine("Creating instance");
		return ObjectFactory.GetInstance(type);
	}
}

public class MyRegistry : Registry
{
	public MyRegistry()
	{
		this.For<ContactsApi>().HttpContextScoped().Use<ContactsApi>();
	}
}

 

Everything seems to work (I haven't integrated NHibernate session handling yet) but I'm not sure I'm doing it right. All the examples I found are using Autofac with custom lifetime.

Oct 20, 2011 at 4:44 PM

Resolved this by using nested container in StructureMap and custom Extension<T> implementation.
It seems to do the same thing as using HttpContextScoped registration and calling ReleaseAndDisposedAllHttpScopedObjects. Below is link to a blob post I wrote about it. It also contains link to github repository where you can find the complete source code for the sample.

http://catchblock.com/blog/post/2011/10/20/Using-StructureMap-with-WCF-Web-API.aspx