I get following exception “Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.” when i try to resolve object from global.asax Application_EndRequest event. I use Autofac in version 2.5.2.830
public class Global : System.Web.HttpApplication, IContainerProviderAccessor
{
// Provider that holds the application container.
static Autofac.Integration.Web.IContainerProvider _containerProvider;
// Instance property that will be used by Autofac HttpModules
// to resolve and inject dependencies.
public Autofac.Integration.Web.IContainerProvider ContainerProvider
{
get { return _containerProvider; }
}
protected void Application_Start(object sender, EventArgs e)
{
var builder = new ContainerBuilder();
...
_containerProvider = new ContainerProvider(builder.Build());
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
ISession session = _containerProvider.RequestLifetime.Resolve<ISession>();
session.BeginTransaction();
}
private void Application_EndRequest(object sender, EventArgs e)
{
ISession session = ContainerProvider.RequestLifetime.Resolve<ISession>();
}
I register in that way:
builder.Register(x => x.Resolve().OpenSession()).As().InstancePerHttpRequest();
}
Autofac does its session disposal through an HttpModule called Autofac.Integration.Web.ContainerDisposalModule.
You need to either
This can be a problem as the order of HttpModules is not guaranteed.
OR
private void Application_EndRequest(object sender, EventArgs e) { ISession session = ContainerProvider.RequestLifetime.Resolve(); //cleanup transaction etc... ContainerProvider.EndRequestLifetime(); }OR
You must make sure to initialize your session manager.