autofac / Autofac.Web

ASP.NET WebForms integration for Autofac
MIT License
10 stars 9 forks source link

IContainerProviderAccessor.ContainerProvider returned null #8

Closed chucklu closed 4 years ago

chucklu commented 4 years ago

IContainerProviderAccessor.ContainerProvider returned null, which is invalid. If the container provider belongs to the HttpApplication subclass, ensure that it is a static variable. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: IContainerProviderAccessor.ContainerProvider returned null, which is invalid. If the container provider belongs to the HttpApplication subclass, ensure that it is a static variable.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

chucklu commented 4 years ago

After troubleshooting I find that a previous person write the register code in static constructor of Global.

static Global(){
// Build up your application container and register your dependencies.
    var builder = new ContainerBuilder();
    builder.RegisterType<SomeDependency>();
    // ... continue registering dependencies...

    // Once you're done registering things, set the container
    // provider up with your registrations.
    _containerProvider = new ContainerProvider(builder.Build());
}

Move the register code to Application_Start method will skip the error "IContainerProviderAccessor.ContainerProvider returned null", and get the real exception.

chucklu commented 4 years ago

@tillig Do you have any idea about this exception? Or maybe we can emphasize that the register code must be written in Application_Start method in documentation.

tillig commented 4 years ago

That's only interesting if you're running web-forms-only, and the example makes it pretty clear. The problem is when folks start mixing web forms with MVC and Web API and OWIN and all these various things - specifying that registrations must be in Application_Start actually becomes more confusing in those instances, because registrations could be elsewhere once you start mixing. I think the documentation is pretty clear with the examples; if folks aren't following the docs, I'm not sure what else to do. I don't think I'm going to take any action here.