ParisaN
ParisaN

Reputation: 2092

How to use AddIdentity<User, Role> in dotnet core 7?

I'm using asp.net core 7 and AspNetCore.Identity 7. I wanna register identity to dependency injection system in IoC layer:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Eshop.Entities;

namespace Eshop.IoCConfig;

public static class AddCustomServicesExtension
{
    public static IServiceCollection AddCustomService(this IServiceCollection services)
    {
        // some code

        services.AddIdentity<User, Role>();

        return services;
    }
}

But there's error:

IServiceCollection does not contain a definition for AddIdentity

Upvotes: 0

Views: 1997

Answers (2)

Snap
Snap

Reputation: 739

The problem is that the AddIdentity extension method used to register the identity services isn't included in the Microsoft.Extensions.DependencyInjection package (even though the API docs show it is oddly enough). It is part of the Microsoft.AspNetCore.Identity package. Add that package to your project and once you import it via a using statement then the method will be available to use to register the desired services.

There's potential issues with using AddIdentitcyCore instead of AddIdentity if you're relying on certain features of the default implementations. The default implementations utilize "token providers" for email confirmation, password reset, two-factor authentication etc. Using the AddIdentitcyCore method does not include them and they have to be manually added while using the AddIdentity method makes the AddDefaultTokenProviders method available that can be used.

If you're not using the features of the token providers then it makes no difference and you can go ahead and use AddIdentitcyCore without registering the token provider services. However if you are then it won't work.

Upvotes: 0

ParisaN
ParisaN

Reputation: 2092

I solved this problem and use AddIdentityCore<TUser> instead of AddIdentity<TUser, TRole>:

 services.AddIdentityCore<User>()
        .AddRoles<Role>()
        .AddEntityFrameworkStores<EshopDbContext>();

Upvotes: 3

Related Questions