Search code examples
c#asp.netasp.net-mvcasp.net-coreasp.net-core-identity

How to resolve the error InvalidOperationException in Microsoft Visual Studio 2019?


When I go to the controller it gives me this error

"InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'AvaliacaoRestaurante.Controllers.FotoController'."

is the problem at startup do I have to add or remove something?

        services.AddDefaultIdentity<ApplicationUser>(options =>
            options.SignIn.RequireConfirmedAccount = true)
                   .AddRoles<IdentityRole>() 
                   .AddEntityFrameworkStores<AvaliacaoRestaurantesDB>();
        services.AddControllersWithViews();

Solution

  • Change your above code in Startup.cs something like that.

        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
                {
                   options.SignIn.RequireConfirmedEmail = true;
                })
                .AddEntityFrameworkStores<AvaliacaoRestaurantesDB>();
               
                services.AddControllersWithViews();
    
    

    And You must use the same class in your controller when injecting it:-

    public FotoController(UserManager<ApplicationUser> userManager)
    

    because you used ApplicationUser in startup, not IdentityUser so this type is not registered with the injection system.I think it's will resolve your issue.