I have got error says:

System.InvalidOperationException: 'Cannot resolve scoped service 'tigerpaw.Models.AppDbContext' from root provider.'

I have absolute no idea what is going on as this is my first mvc project. Please let me know if more information is need. Any kind of help or suggestion are greatly appreciated. Thank you

My startup class

public class Startup
    {
        private IConfigurationRoot _configurationRoot;

        public Startup(IHostingEnvironment hostingEnvironment)
        {
            _configurationRoot = new ConfigurationBuilder()
                .SetBasePath(hostingEnvironment.ContentRootPath)
                .AddJsonFile("appsettings.json")
                .Build();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppDbContext>(options => options.UseSqlServer(_configurationRoot.GetConnectionString("DefaultConnection")));
            services.AddTransient<ICategoryRepository, CategoryRepository>();
            services.AddTransient<IToyRepository, ToyRepository>();
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseDeveloperExceptionPage(); //adding expection that's not in default
            app.UseStatusCodePages();// respon status code 400-600
            app.UseStaticFiles();// server static files
            app.UseMvcWithDefaultRoute(); //adding support for mvc

            DbInitializer.Seed(app);
        }
    }

Here is my Dbinitializer

public static void Seed(IApplicationBuilder applicationBuilder)
        {
            AppDbContext context = applicationBuilder.ApplicationServices.GetRequiredService<AppDbContext>();

            if (!context.Categories.Any())
            {
                context.Categories.AddRange(Categories.Select(c => c.Value));
            }
            if (!context.SmallToys.Any())
            {
                context.AddRange
                    (

                        new Toy { Name = "Mickey mouse", Price = 19.5M, ShortDescription = "12cm small size soft toy for any ages", Category = Categories["Small Size toys"], InStock = true, ImageUrl = "/Images/mickey-mouse-toy.jpg" },
                        new Toy { Name = "Teddy Bear", Price = 19.5M, ShortDescription = "14cm small size soft toy for any ages", Category = Categories["Small Size toys"], InStock = true, ImageUrl = "https://images-na.ssl-images-amazon.com/images/I/914blLD4RCL._SX425_.jpg" },
                        new Toy { Name = "Rabbit", Price = 19.5M, ShortDescription = "14cm small size soft toy for any ages", Category = Categories["Small Size toys"], InStock = true, ImageUrl = "https://images-na.ssl-images-amazon.com/images/I/31i4-mrHt6L._SX355_.jpg" }


                    );
            }
            context.SaveChanges();
        }

        private static Dictionary<string, Category> categories;
        public static Dictionary<string, Category> Categories
        {
            get
            {
                if (categories == null)
                {
                    var genresList = new Category[]
                    {
                        new Category { CategoryName = "Large Size toys"},
                        new Category { CategoryName = "Medium Size toys"},
                        new Category { CategoryName = "Small Size toys"}
                    };

                    categories = new Dictionary<string, Category>();

                    foreach (Category genre in genresList)
                    {
                        categories.Add(genre.CategoryName, genre);
                    }
                }

                return categories;
            }
        }

AppDbContext


    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {

        }

        public DbSet<Category> Categories { get; set; }
        public DbSet<Toy> SmallToys { get; set; }
    }

the error that show up on my browser when i run it

An error occurred while starting the application.
InvalidOperationException: Cannot resolve scoped service 'tigerpaw.Models.AppDbContext' from root provider.
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)

InvalidOperationException: Cannot resolve scoped service 'tigerpaw.Models.AppDbContext' from root provider.
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)
Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType)
Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<T>(IServiceProvider provider)
tigerpaw.Models.DbInitializer.Seed(IApplicationBuilder applicationBuilder) in DbInitializer.cs
-
namespace tigerpaw.Models
{
    public class DbInitializer
    {
        public static void Seed(IApplicationBuilder applicationBuilder)
        {
            AppDbContext context = applicationBuilder.ApplicationServices.GetRequiredService<AppDbContext>(); // this line is in red
            if (!context.Categories.Any())
            {
                context.Categories.AddRange(Categories.Select(c => c.Value));
            }
            if (!context.SmallToys.Any())
tigerpaw.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env) in Startup.cs
-
        {
            app.UseDeveloperExceptionPage(); //adding expection that's not in default
            app.UseStatusCodePages();// respon status code 400-600
            app.UseStaticFiles();// server static files
            app.UseMvcWithDefaultRoute(); //adding support for mvc
            DbInitializer.Seed(app); // also this line is in red
        }
    }
}
Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
Microsoft.AspNetCore.Server.IISIntegration.IISSetupFilter+<>c__DisplayClass4_0.<Configure>b__0(IApplicationBuilder app)
Microsoft.AspNetCore.HostFilteringStartupFilter+<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter+<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder builder)
Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

Related posts

Recent Viewed