ASP.NET WebApi2 controller
public class BooksController : ApiController { public IRepository Repository { get; set; } public BooksController(IRepository r) { Repository = r; } ... } Repository:
public class BookRepository : IRepository, IDisposable { public BookContext Context { get; set; } ... protected void Dispose(bool disposing) { if (disposing) { if (Context != null) { Context.Dispose(); Context = null; } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } Data context:
public class BookContext : DbContext { public DbSet<Book> Books { get; set; } } Autofac is used as IoC, the container is configured in Global.asax:
protected void Application_Start() { AutofacConfig.ConfigureContainer(); . . . } public class AutofacConfig { public static void ConfigureContainer() { var builder = new ContainerBuilder(); var config = GlobalConfiguration.Configuration; builder.RegisterType<BookRepository>().InstancePerRequest().As<IRepository>().WithProperty("Context", new BookContext()); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); var container = builder.Build(); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); } } For some reason, with such a registration of the BookRepository type, a new instance of its Context property is not created with a new http request. That is, the first http-request to the API works, and the second one returns the following error: The operation cannot be completed because the DbContext has been disposed.