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

Viewed 174

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();
2 Answers

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.

Did you register identity in your ConfigureServices method (class Startup)? You have to find a line like the following:

services.AddIdentity<UserIdentity, RoleIdentity>(...)

Related