How to use Autofac with WCF Web API
The new configuration model in the latest WCF Web APIs allows extending the service instantiation via what is called a resource factory.
For Autofac, I wanted to support a per-request lifetime scope, so I used the concept of instance context extensions in the Web APIs to place our scope so that it can be disposed on release.
public class AutofacResourceFactory : IResourceFactory
private IContainer container;
public AutofacResourceFactory(IContainer container)
this.container = container;
public object GetInstance(Type serviceType, InstanceContext instanceContext, HttpRequestMessage request)
// Begin lifetime scope when the service is instantiated.
var lifetime = this.container.BeginLifetimeScope();
// Hold the lifetime as an extension in the instance context
public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext, object service)
var extension = instanceContext.Extensions.OfType<AutofactLifetimeExtension>().FirstOrDefault();
// If we find our extension there, dispose it so the lifetime gets disposed.
if (extension != null)
private class AutofactLifetimeExtension : IExtension<InstanceContext>, IDisposable
private ILifetimeScope lifetime;
private bool isDisposed;
public AutofactLifetimeExtension(ILifetimeScope lifetime)
this.lifetime = lifetime;
public void Attach(InstanceContext owner)
public void Detach(InstanceContext owner)
public void Dispose()
this.isDisposed = true;
Read full article