Autofac throws an ObjectDisposedException

I recently added Autofac 2.6.2 to one of my ASP.NET MVC projet.

I'm facing an issue, when I want to Resolve my WebDataContext I have an ObjectDisposedException:

Instances cannot be resolved and nested lifetimes cannot be
created from this LifetimeScope as it has already been disposed.

When I call my Index page, my browser sends many requests to get the index page and all other resources needed (css, js and so on). One of these requests can resolve the IWebDataContext and all others throw the ObjectDisposedException.

So my code looks something like this:

protected void Application_Start()
{
    MyContext.Initialize();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(MyContext.Container));
    [...]
}

public class MyContext
{
    public static IContainer Container { get; set; }

    public static void Initialize()
    {
        ContainerBuilder container = new ContainerBuilder();
        IDependencyRegistrar registrar = new DependencyRegistrar();
        registrar.Register(container);
        MyContext.Container = container.Build();
    }

    public static IEngine Engine
    {
        get { return Singleton<IEngine>.Instance; }
    }
}

public class DependencyRegistrar : IDependencyRegistrar
{
    public void Register(object containerBuilder)
    {
        ContainerBuilder builder = (ContainerBuilder)containerBuilder;
        builder.RegisterControllers(Assembly.GetExecutingAssembly());
        builder.RegisterType<WebDataContext>().As<IWebDataContext>().InstancePerHttpRequest();
            [...]
}

And finally the way I resolve my registered dependencies:

public class MyEngine : IEngine
{
    public T Resolve<T>() where T : class
    {
        return DependencyResolver.Current.GetService<T>();
    }
}

What I think: one thread disposes the WebDataContext and all other threads can no longer access it. Can someone tell me if I forget something and if my code is thread safe ?

Answers


I found the issue, I was calling the Resolve method in my Application_Error event what is not possible because autofac disposes its resources before !


Need Your Help

Authentication with JWT and JSONAPI

rest authentication jwt json-api

I am implementing REST API using the following technologies/approaches:

How to stream a local file to the Chromecast?

ios google-cast

Is it possible to stream a local file from an iOS app bundle to the Chromecast ?