locked
InvalidOperationException: Unable to resolve service for type RRS feed

  • Question

  • User-605499000 posted

    Microsoft.AspNetCore.Identity.SignInManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Bumples.Controllers.AccountController'.

    Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

    Hi, I am trying to load a very simple register program. Below are the programs involved.  I am using asp.net core mvc 3.0

    Controller

    using System.Threading.Tasks;
    using Bumples.ViewModels;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.AspNetCore.Mvc;
    using Bumples.ViewModels;
    namespace Bumples.Controllers
    {
        public class AccountController : Controller
        {
            private readonly UserManager<IdentityUser> userManager;
            private readonly SignInManager<IdentityUser> signInManager;
            public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
            {
                this.userManager = userManager;
                this.signInManager = signInManager;
            }
            public IActionResult Register()
            {
                return View();
            }
            [HttpPost]
            public async Task<IActionResult> Register(RegisterViewModel model)
            {
                if (ModelState.IsValid)
                {
                    var user = new IdentityUser
                    {
                        UserName = model.Email,
                        Email = model.Email
                    };
                    var result = await userManager.CreateAsync(user, model.Password);
                    if (result.Succeeded)
                    {
                        await signInManager.SignInAsync(user, isPersistent: false);
                        return RedirectToAction("Index", "Home");
                    }
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
                return View();
            }
        }
    }
    Model
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Threading.Tasks;
    namespace Bumples.ViewModels
    {
        public class RegisterViewModel
        {
            [Required]
            [EmailAddress]
            public string Email { get; set; }
            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }
            [Required]
            [Display(Name = "Confirm Password")]
            [DataType(DataType.Password)]
            [Compare("Password", ErrorMessage = "Your password and confirm password do not match")]
            public string ConfirmPassword { get; set; }
        }
    }

    startup

    using Bumples.Models;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    namespace Bumples
    {
        public class Startup
        {
            private readonly IConfiguration Configuration;
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
            public void ConfigureServices(IServiceCollection services)
            {
                //Add Connection Middleware   
                services.AddDbContext<ApplicationDbContext>(
                    options => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));
                //Configure Identity framework core 
                services.AddIdentityCore<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                     .AddEntityFrameworkStores<ApplicationDbContext>();
                //Add MVC Middleware   
                services.AddControllersWithViews();
                services.AddRazorPages();
            }
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                app.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseRouting();
                //Add Authentication and Authorization before route  
                app.UseAuthentication();
                app.UseAuthorization();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }
    Where am I going wrong,
    Thanks Jen
    Monday, March 2, 2020 6:59 PM

Answers

  • User-605499000 posted

    Thanks you very much for your help. That did the job.  I have been using bootstrap for years and am using it now so not sure why I had the problem or told to use Bower.

    I am not a programmer although I have been learning a lot, I have used the forums and they have helped me so much.

    Thanks again,

    Jen

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, March 4, 2020 2:54 PM

All replies

  • User-854763662 posted

    Hi bumples18 ,

    AddIdentityCore adds the services that are necessary for user-management actions ( this boils down to registering an instance of UserManager<TUser> ), such as creating users, hashing passwords, etc. Refer to the relevant source.

    AddIdentity registers the same services as AddIdentityCore, with a few extras:

    • Cookie-based authentication schemes for the application itself, external sign-in (e.g. Facebook and Google), and 2FA.
    • The SignInManager, which effectively sits on top of the UserManager as a sort of orchestrator. For example, PasswordSignInAsync uses UserManager to retrieve a user, verify the password (if set) and then takes care of cookie creation.
    • AddIdentity itself also takes a TRole and registers the services that are necessary for supporting Roles.

    Refer to the relevant source.

    Calling AddDefaultIdentity is similar to calling the following:

    1. AddIdentity

    2. AddDefaultUI

    3. AddDefaultTokenProviders

    So change the below code line

    services.AddIdentityCore<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();

    to

    services
    //.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddIdentity<IdentityUser,IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddDefaultUI()
    .AddDefaultTokenProviders(); .AddEntityFrameworkStores<ApplicationDbContext>();

    Best Regards,

    Sherry

    Tuesday, March 3, 2020 4:11 AM
  • User-605499000 posted

    Hi Sherry,

    Thank you for your help. I did what you said but I am getting a bootstrap error in the startup file.  I reloaded bootstrap using NuGet but they said to use bower which I uploaded. Bower has a separate file bower_component.  

    The error in the startup is the following: object does not contain a definition for Bootstrap4 and no accessible extension method Bootstrap4 accepting a first argument of type object could not be found( are you missing a using directive or an assembly.

    Under layout.tshtml  I have 

    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    <script src="~/js/CustomScript.js"></script>
    @RenderSection("Scripts", required: false)

    How do I resolve this problem?

    Jen

    Tuesday, March 3, 2020 6:19 PM
  • User-854763662 posted

    Hi bumples18 ,

    Actually , AddDefaultUI adds a default, self-contained UI for Identity to the application using Razor Pages in an area named Identity. You could remove it in mvc project and it has no effect. And bootstrap4 has been used since ASP.NET Core 2.2 ,you could refer to this blog .

    So in your ConfigureServices, you could use  AddDefaultIdentity best

    services.AddDefaultIdentity<IdentityUser>()
                    .AddEntityFrameworkStores<ApplicationDbContext>();

    Best Regards,

    Sherry

    Wednesday, March 4, 2020 9:41 AM
  • User-605499000 posted

    Thanks you very much for your help. That did the job.  I have been using bootstrap for years and am using it now so not sure why I had the problem or told to use Bower.

    I am not a programmer although I have been learning a lot, I have used the forums and they have helped me so much.

    Thanks again,

    Jen

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, March 4, 2020 2:54 PM