I am making a rest service using ServiceStack (http://www.servicestack.net). I’m using the unit of work pattern for my data access layer. I am using StructureMap to connect all my services and the unit of work together.
What I need to do is to create a single unit of work for each individual request that I receive and then dispose of it after.
I have a WCF Service which is using the mechanism here, http://andreasohlund.net/2009/04/27/unitofwork-in-wcf-using-structuremap.
Essentially resulting in something like this
ObjectFactory.Initialize(x =>
{
x.Scan(a =>
{
a.AssemblyContainingType<IUnitOfWork>();
a.WithDefaultConventions();
});
x.For<IUnitOfWork>().LifeCycleIs(new WcfOperationLifecycle());
}
I am looking for a similar ‘Lifecycle’ for ServiceStack.
[Solution]
The solution is in the comments of the accepted answer.
a) Set the StructureMap lifecycle to HttpContext
x.For<IUnitOfWork>().LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.HttpContext));
b) Updated the structure map IOC adapter to extend the IRelease interface
class StructureMapContainerAdapter : IContainerAdapter, IRelease
{
public T Resolve<T>()
{
return ObjectFactory.GetInstance<T>();
}
public T TryResolve<T>()
{
return ObjectFactory.TryGetInstance<T>();
}
public void Release(object instance)
{
ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}
}
Sounds like you just want Request Scope?
Also check out the concrete Service base class on how you can use Lazy loading +
Dispose()to get this behaviour.As well as in ServiceStack’s new API you can override your services
OnBeforeExecute()OnAfterExecute()event hooks by using your own ServiceRunner (in the older API you would need to provide a custom service base class).