6

I will seed data into AspNet Identity Table. The table created successfully but I get an error when trying to seeding data.

System.InvalidOperationException: 'Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger1[Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser]]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]

 public static void EnsureSeedData(string connectionString)
            {
                var services = new ServiceCollection();
                services.AddDbContext<IdentityDbContext>(options =>
                   options.UseSqlServer(connectionString));

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

                using (var serviceProvider = services.BuildServiceProvider())
                {
                    using (var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
                    {
                        var context = scope.ServiceProvider.GetService<IdentityDbContext>();
                        context.Database.Migrate();

                        var userMgr = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
                        var alice = userMgr.FindByNameAsync("alice").Result;
                        if (alice == null)
                        {
                            alice = new ApplicationUser
                            {
                                UserName = "alice",
                                Email = "AliceSmith@email.com",
                                EmailConfirmed = true
                            };
                            var result = userMgr.CreateAsync(alice, "My long 123$ password").Result;
                            if (!result.Succeeded)
                            {
                                throw new Exception(result.Errors.First().Description);
                            }

                            result = userMgr.AddClaimsAsync(alice, new Claim[]{
                            new Claim(JwtClaimTypes.Name, "Alice Smith"),
                            new Claim(JwtClaimTypes.GivenName, "Alice"),
                            new Claim(JwtClaimTypes.FamilyName, "Smith"),
                            new Claim(JwtClaimTypes.Email, "AliceSmith@email.com"),
                            new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                            new Claim(JwtClaimTypes.WebSite, "http://alice.com"),
                            new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServer4.IdentityServerConstants.ClaimValueTypes.Json)
                        }).Result;
                            if (!result.Succeeded)
                            {
                                throw new Exception(result.Errors.First().Description);
                            }
                            Console.WriteLine("alice created");
                        }
                        else
                        {
                            Console.WriteLine("alice already exists");
                        }

                        var bob = userMgr.FindByNameAsync("bob").Result;
                        if (bob == null)
                        {
                            bob = new ApplicationUser
                            {
                                UserName = "bob",
                                Email = "BobSmith@email.com",
                                EmailConfirmed = true
                            };
                            var result = userMgr.CreateAsync(bob, "My long 123$ password").Result;
                            if (!result.Succeeded)
                            {
                                throw new Exception(result.Errors.First().Description);
                            }

                            result = userMgr.AddClaimsAsync(bob, new Claim[]{
                            new Claim(JwtClaimTypes.Name, "Bob Smith"),
                            new Claim(JwtClaimTypes.GivenName, "Bob"),
                            new Claim(JwtClaimTypes.FamilyName, "Smith"),
                            new Claim(JwtClaimTypes.Email, "BobSmith@email.com"),
                            new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                            new Claim(JwtClaimTypes.WebSite, "http://bob.com"),
                            new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServer4.IdentityServerConstants.ClaimValueTypes.Json),
                            new Claim("location", "somewhere")
                        }).Result;
                            if (!result.Succeeded)
                            {
                                throw new Exception(result.Errors.First().Description);
                            }
                            Console.WriteLine("bob created");
                        }
                        else
                        {
                            Console.WriteLine("bob already exists");
                        }
                    }
                }
            }
            public static void EnsureSeedData(string connectionString, UserManager<ApplicationUser> userManager)
            {
                //  SeedRoles(roleManager);
                SeedUsers(userManager);
            }

            public static void SeedUsers(UserManager<ApplicationUser> userManager)
            {
                if (userManager.FindByNameAsync
    ("user1").Result == null)
                {
                    ApplicationUser user = new ApplicationUser();
                    user.UserName = "user1";
                    user.Email = "user1@localhost";
                    //user.FullName = "Nancy Davolio";
                    //user.BirthDate = new DateTime(1960, 1, 1);

                    IdentityResult result = userManager.CreateAsync
                    (user, "P@ssw0rd1").Result;

                    if (result.Succeeded)
                    {
                        userManager.AddToRoleAsync(user,
                                            "NormalUser").Wait();
                    }
                }


                if (userManager.FindByNameAsync
            ("user2").Result == null)
                {
                    ApplicationUser user = new ApplicationUser();
                    user.UserName = "user2";
                    user.Email = "user2@localhost";
                    //user.FullName = "Mark Smith";
                    //user.BirthDate = new DateTime(1965, 1, 1);

                    IdentityResult result = userManager.CreateAsync
                    (user, "P@ssw0rd1").Result;

                    if (result.Succeeded)
                    {
                        userManager.AddToRoleAsync(user,
                                            "Administrator").Wait();
                    }
                }
            }

            public static void SeedRoles(RoleManager<IdentityRole> roleManager)
            {
                if (!roleManager.RoleExistsAsync
    ("NormalUser").Result)
                {
                    IdentityRole role = new IdentityRole();
                    role.Name = "NormalUser";
                    //role.Description = "Perform normal operations.";
                    IdentityResult roleResult = roleManager.
                    CreateAsync(role).Result;
                }


                if (!roleManager.RoleExistsAsync
            ("Administrator").Result)
                {
                    IdentityRole role = new IdentityRole();
                    role.Name = "Administrator";
                    // role.Description = "Perform all the operations.";
                    IdentityResult roleResult = roleManager.
                    CreateAsync(role).Result;
                }
            }
            public static async Task<IdentityResult> AssignRoles(IServiceProvider services, string email, string[] roles)
            {
                UserManager<ApplicationUser> _userManager = services.GetService<UserManager<ApplicationUser>>();
                ApplicationUser user = await _userManager.FindByEmailAsync(email);
                var result = await _userManager.AddToRolesAsync(user, roles);

                return result;
            }*

*--------------------------Program.cs -------------------------------------
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


using IdentityServer.Data.Seed;
using IdentityServer.Models;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;
using System;
using System.Linq;

namespace IdentityServer
{
    public class Program
    {
        public static void main(string[] args)
        {
            Console.Title = "identityserver4";

            var host = CreateWebHostBuilder(args).Build();

            var config = host.Services.GetRequiredService<IConfiguration>();
            bool seed = config.GetSection("data").GetValue<bool>("seed");
            if (seed)
            {
                var connectionstring = config.GetConnectionString("identityconn");
                Users.EnsureSeedData(connectionstring);
            }

            host.Run();
        }


        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                    .UseStartup<Startup>()
                    .UseSerilog((context, configuration) =>
                    {
                        configuration
                            .MinimumLevel.Debug()
                            .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                            .MinimumLevel.Override("System", LogEventLevel.Warning)
                            .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
                            .Enrich.FromLogContext()
                            .WriteTo.File(@"identityserver4_log.txt")
                            .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Literate);
                    });
        }
    }
}*
Pankwood
  • 1,799
  • 5
  • 24
  • 43
  • you need to register your ILogget based on your error? Are you familiar with DI?Please also add your Startup.cs – panoskarajohn Dec 13 '19 at 12:17
  • Take a look at this -> https://stackoverflow.com/questions/54570904/unable-to-resolve-service-for-type-microsoft-extensions-logging-ilogger1webap – panoskarajohn Dec 13 '19 at 12:20
  • Also, you shouldn't be seeding like this. This was the way you had to do it in 1.x, but EF Core now has built-in functionality for this. See: https://learn.microsoft.com/en-us/ef/core/modeling/data-seeding – Chris Pratt Dec 13 '19 at 14:12
  • @panoskarajohn I was unable to solve it i try what is in the link you sent but still the same. please kind help futher and give and example of how to seed aspnet idenity user and user claim to role in .net 3.0 – MUYIDEEN KAZEEM Dec 13 '19 at 21:44
  • @ChrisPratt can you help with code snippet for seeding user, user claim and role. thanks – MUYIDEEN KAZEEM Dec 13 '19 at 21:46
  • Still cant figure it out – MUYIDEEN KAZEEM Dec 13 '19 at 22:07

1 Answers1

8

If you like me ended up here after following a tutorial.

You missed services.AddLogging

public static void EnsureSeedData(string connectionString)
{
    var services = new ServiceCollection();
    services.AddLogging();
...
HackSlash
  • 4,944
  • 2
  • 18
  • 44
phastari
  • 81
  • 1
  • 2