Autofac and ServiceStack - Managing Life Cycle

If you ever used Autofac with MVC or WebAPI, you know that integration modules provide you an ability to register your dependencies with life time scope that matches the HTTP request life cycle. However, when you are using ServiceStack, life becomes a bit more complicated.

ServiceStack natively uses Funq and supports per-request life cycle with this container. You can provide an adapter for your own container but then the life cycle control is in your hands, ServiceStack will do nothing to help you there.

I am using Autofac container in most of my projects so it quickly became apparent that some dependencies have to be disposed at the end of the HTTP request.

After reading some Autofac documentation, I did this by starting new scope at HTTP request start and disposing it at request end, and using the scope in my container adapter, if available.

When using this sort of life cycle management, you can use Autofac native .InstancePerRequest() in your registrations.

The new adapter code looks like this:



And this is my Global.asax.cs
Note that this only works when ServiceStack is hosted on IIS. For more generic solution, check the latest version.

See also