17

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]'.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
nikovn
  • 1,900
  • 5
  • 22
  • 28

3 Answers3

10

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.

Mihail Stancescu
  • 4,088
  • 1
  • 16
  • 21
  • I mentioned above that I didn't (since I don't intend to use it for authentication - only userstores). However, even after adding it experimentally the result is the same. – nikovn Jan 16 '17 at 15:18
  • 2
    Your edit fixed it and now I'm embarrassed. I'll hide my face for the rest of the day... – nikovn Jan 16 '17 at 15:33
  • 29
    Mihail mentions adding app.UseIdentity(). This has been deprecated in CORE 2.0. The method now is app.UseAuthentication(). Hope this helps. – EoRaptor013 Mar 21 '18 at 21:35
  • 7
    `UseAuthentication()` doesn't seem to register these managers either. – Sinaesthetic Oct 13 '18 at 22:17
  • What if I don't use a db context? – Markus Ende Jul 11 '19 at 10:41
  • @Mihail Stancescu so does it mean that `services.AddIdentity()` inject `UserManager`? –  Aug 22 '19 at 23:45
5

DI container is unable to resolve a dependency. Add it to the services collection

services.AddTransient<UserManager<ApplicationUser>>();
services.AddTransient<ApplicationDbContext>();

You should also familiarize yourself with the official documentation

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • 2
    It's exactly this documentation that claims that everything is available via DI after using services.AddIdentity(), which doesn't work unfortunately. Tried this solution, in addition to adding transient user stores, password validators and all visible dependencies in the UserStore constructor - still nothing. – nikovn Jan 16 '17 at 15:17
  • 1
    Ok understood. Can you add a [mcve] of the problem so that we can reproduce your problem and be in a position to provide better answers – Nkosi Jan 16 '17 at 15:19
-1
public void ConfigureServices(IServiceCollection services){
...
var identityBuilder = services.AddIdentityCore<ApplicationUser>(user =>
            {
                // configure identity options
                user.Password.RequireDigit = true;
                user.Password.RequireLowercase = false;
                user.Password.RequireUppercase = false;
                user.Password.RequireNonAlphanumeric = false;
                user.Password.RequiredLength = 6;
            });
            identityBuilder = new IdentityBuilder(identityBuilder.UserType, typeof(IdentityRole), identityBuilder.Services);
            identityBuilder.AddEntityFrameworkStores<DbContext>().AddDefaultTokenProviders();
    ...
}
Lakmal
  • 779
  • 1
  • 8
  • 16