Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to resolve service for type IEmailSender while attempting to activate RegisterModel

I'm using Identity and I have a problem that I make a new example project and with individual authentication and scaffold identity InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UI.Services.IEmailSender' while attempting to activate 'MASQ.Areas.Identity.Pages.Account.RegisterModel'.

like image 332
Muhammad Abdullah Avatar asked Aug 30 '18 05:08

Muhammad Abdullah


4 Answers

I am using ASP.NET Core 3.0 and had similar issue. I added the following .AddDefaultUI() to my Startup.cs & it worked.

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddIdentity<IdentityUser, IdentityRole>()
                .AddDefaultTokenProviders()
                .AddDefaultUI()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddControllersWithViews();
            services.AddRazorPages().AddRazorRuntimeCompilation();
        }
like image 64
Walker Avatar answered Oct 17 '22 00:10

Walker


There're two ways to do that :

  1. remove the services.AddDefaultTokenProviders() in the ConfigurureServices() to disable two-factor authentication (2FA) :
    // file: `Startup.cs` :
    services.AddDefaultIdentity<IdentityUser>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
        ///.AddDefaultTokenProviders(); /// remove this line
    
  2. Add your own IEmailSender and ISmsSender implementation to DI contianer if you would like to enable 2FA

    // file: `Startup.cs`
    
    services.AddTransient<IEmailSender,YourEmailSender>();
    services.AddTransient<IEmailSender,YourSmsSender>();
    

Edit:

Both should work.

Both should work for ASP.NET Core 2.1. However, as of ASP.NET Core 3.0, the first approach doesn't work any more.

like image 42
itminus Avatar answered Oct 17 '22 00:10

itminus


Add Default UI in the configuration service:

services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders()
    .AddDefaultUI();
like image 6
Tsega Avatar answered Oct 17 '22 02:10

Tsega


For ASP.NET Core 5.0 you can use the following code, instead of calling AddIdentity

services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<AppDbContext>()
            .AddDefaultTokenProviders();
like image 2
axelio Avatar answered Oct 17 '22 02:10

axelio