2

We are currently using autofac in our mvc web app.

Build() or Update() can only be called once on a ContainerBuilder

Every 1-4 days we get the error noted above. It's driving me crazy. I've been trying to see why it would be doing this but I can't pinpoint the issue.

Can someone point me in the right direction.

Prescient
  • 1,051
  • 3
  • 17
  • 42
  • Where are you calling it? – Marc L. Apr 16 '14 at 04:18
  • on application start. I think we've tracked down the issue to being , since it usually happens early in am or on weekends, when 2 users hit the site at the same time call the startup process and invoke build at the same time. – Prescient Apr 16 '14 at 15:05

2 Answers2

2

I encountered the same thing in my application (.Net Core 3.1) I wanted to get the Container and resolve registered services.

In .Net Core 3.1 you can't simply change Startup.ConfigureServices method to return IServiceProvider as it was in previous versions

So, to get the services you need in your Startup void Configure(IApplicationBuilder app) method call app.ApplicationServices.GetAutofacRoot() this will return ILifetimeScope instance you can use to resolve services

Note. Consider that saving this instance globally is not the best practice

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //app middleware registrations 
            //...
            //

            ILifetimeScope autofacRoot = app.ApplicationServices.GetAutofacRoot();
            var repository = autofacRoot.Resolve<IRepository>();
        }
simply good
  • 991
  • 1
  • 12
  • 26
1

Unless you have start-up processes that require HttpApplication resources, I would recommend removing application initialization to a static constructor or a completely separate singleton. I have seen similar issues with Application_Start(), you need a structure that is guaranteed to be called just once.

Marc L.
  • 3,296
  • 1
  • 32
  • 42