Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.InvalidOperationException: 'Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1

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 = "[email protected]",
                                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, "[email protected]"),
                            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 = "[email protected]",
                                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, "[email protected]"),
                            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);
                    });
        }
    }
}*
like image 318
MUYIDEEN KAZEEM Avatar asked Dec 13 '19 12:12

MUYIDEEN KAZEEM


1 Answers

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();
...
like image 200
phastari Avatar answered Sep 23 '22 00:09

phastari