C# – ASP.NET Core Identity does not inject UserManager

asp.net-coreasp.net-core-mvcasp.net-identityasp.net-web-apic

I've got an older asp.net core identity database, and I want to map a new project (a web api) to it.

Just for the test, I copied the Models folder, and the ApplicationUser file from the previous project (ApplicationUser simply inherits from IdentityUser, no changes whatsoever) – doing DB first seems to be a bad idea.

I'm registering Identity in ConfigureServices (but I'm not adding it to the pipeline since my only intention is to use the UserStore)

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

My expectation is that now

     UserManager<ApplicationUser>

…should be automatically injected into constructors.

However, when adding the following code to a controller
private UserManager _userManager;

    public UserController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

… every call to the api ends with an exception:
HttpRequestException: Response status code does not indicate success: 500 (Internal Server Error).

Removing the "injection" code results in smoothly running web api that can accept requests.

It's hard to debug as this occurs before any of my code is reached. Any idea why this is occurring?

P.S. After enabling all exceptions from the Exception Settings window I got this one:

Exception thrown: 'System.InvalidOperationException' in
Microsoft.Extensions.DependencyInjection.dll

Additional information: Unable to resolve service for type
'Namespace.Data.ApplicationDbContext' while attempting to activate
'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`4[Namespace.Models.
ApplicationUser,Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole,Namespace.Data.ApplicationDbContext,System.String]'.

Best Answer

Do you have the app.UseIdentity(); call in the Configure method:

 public void Configure(IApplicationBuilder app, 
                       IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        /*...*/
        app.UseIdentity();
       /*...*/          
    }

EDIT Do you also have this line before the services.AddIdentity<ApplicationUser, IdentityRole>() line?

 public void ConfigureServices(IServiceCollection services)
 {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
             options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

 }

This should work OK. Also please check if ApplicationDbContext inherits from IdentityDbContext.