Search code examples
controllerasp.net-mvc-4autofacrequestfactory

single instance of controller cannot be used to handle multiple requests - Autofac


I am using Autofac.ContainerBuilder in my ASP.Net MVC 4 application, that is giving a problem with default controllers to generate multiple instances.

i tried to handle it this way

 builder.RegisterType<AccountController>().As<IController>().PreserveExistingDefaults();

but no use.

Code

protected void Application_Start()
    {

      var dataPath = "~/App_Data/" + ConfigurationManager.AppSettings["Blog_Site"];

        var builder = new ContainerBuilder();

        builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>().InstancePerHttpRequest();
        builder.RegisterControllers(Assembly.GetExecutingAssembly()).InjectActionInvoker().InstancePerHttpRequest();

        builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
        builder.RegisterType<JsonRepository>().As<IRepository>().InstancePerLifetimeScope().WithParameter("dataPath", HttpContext.Current.Server.MapPath(dataPath));
        builder.RegisterType<ConfigService>().As<IConfigService>().InstancePerLifetimeScope();
        builder.RegisterType<EntryService>().As<IEntryService>().InstancePerLifetimeScope();
        builder.RegisterType<UserService>().As<IUserService>().InstancePerLifetimeScope();
        builder.RegisterType<MessageService>().As<IMessageService>().InstancePerLifetimeScope();
        builder.RegisterType<CloudService>().As<ICloudService>().InstancePerLifetimeScope();
        builder.RegisterType<Services>().As<IServices>().InstancePerLifetimeScope();

        _containerProvider = new ContainerProvider(builder.Build());

        ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(ContainerProvider));

        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(System.Web.Optimization.BundleTable.Bundles);
        AuthConfig.RegisterAuth();

        HtmlHelper.ClientValidationEnabled = true;
        HtmlHelper.UnobtrusiveJavaScriptEnabled = true;

        // Quartz.NET scheduler
        ISchedulerFactory factory = new StdSchedulerFactory();
        var scheduler = factory.GetScheduler();
        scheduler.JobFactory = new AutofacJobFactory(ContainerProvider);
        scheduler.Start();
    }

When i try to access default controller Account/Manage i get below error.

This i how view is calling

  @Html.Action("RemoveExternalLogins")

    <h3>Add an external login</h3>
    @Html.Action("ExternalLoginsList", new { ReturnUrl = ViewBag.ReturnUrl })

Controller

  public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

Error Message

   A single instance of controller 'MVC.Controllers.AccountController' cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request.

How can i fix this problem?


Solution

  • this did the trick

    builder.RegisterType<AccountController>().InstancePerDependency();