无法从 ASP.NET Core 6 中的根提供程序解析作用域服务

Noa*_*lan 14 c# asp.net-core-6.0

我正在使用 ASP.NET Core 6 编写一个网站。它最初是来自 YouTube 的 .NET Core 3 教程。所以我面临迁移问题。\n这里,我有一个 DbInitializer 文件,其中包含我的所有数据(即:我的数据库)。

\n
using DrinkAndGo.Data.Models;\nusing Microsoft.AspNetCore.Builder;\nusing Microsoft.Extensions.DependencyInjection;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace DrinkAndGo.Data\n{\npublic class DbInitializer\n{\n    public static void Seed(IApplicationBuilder applicationBuilder)\n    {\n        AppDbContext context =\n            applicationBuilder.ApplicationServices.GetRequiredService<AppDbContext>();\n\n        if (!context.Categories.Any())\n        {\n            context.Categories.AddRange(Categories.Select(c => c.Value));\n        }\n\n        if (!context.Drinks.Any())\n        {\n            context.AddRange\n            (\n                new Drink\n                {\n                    Name = "Beer",\n                    Price = 7.95M,\n                    \n                    Category = Categories["Alcoholic"],\n                    ImageUrl = "http://imgh.us/beerL_2.jpg",\n                    InStock = true,\n                    IsPreferredDrink = true,\n                    ImageThumbnailUrl = "http://imgh.us/beerS_1.jpeg"\n                },\n                new Drink\n                {\n                    Name = "Rum & Coke",\n                    Price = 12.95M,\n                    \n                    Category = Categories["Alcoholic"],\n                    ImageUrl = "http://imgh.us/rumCokeL.jpg",\n                    InStock = true,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/rumAndCokeS.jpg"\n                },\n                new Drink\n                {\n                    Name = "Tequila ",\n                    Price = 12.95M,\n                    \n                    Category = Categories["Alcoholic"],\n                    ImageUrl = "http://imgh.us/tequilaL.jpg",\n                    InStock = true,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/tequilaS.jpg"\n                },\n                new Drink\n                {\n                    Name = "Wine ",\n                    Price = 16.75M,\n                    \n                    Category = Categories["Alcoholic"],\n                    ImageUrl = "http://imgh.us/wineL.jpg",\n                    InStock = true,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/wineS.jpg"\n                },\n                new Drink\n                {\n                    Name = "Margarita",\n                    Price = 17.95M,\n                   \n                    ImageUrl = "http://imgh.us/margaritaL.jpg",\n                    InStock = true,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/margaritaS.jpg"\n                },\n                new Drink\n                {\n                    Name = "Whiskey with Ice",\n                    Price = 15.95M,\n                    \n                    Category = Categories["Alcoholic"],\n                    ImageUrl = "http://imgh.us/whiskyIceL.jpg",\n                    InStock = false,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/whiskeyS.jpg"\n                },\n                new Drink\n                {\n                    Name = "J\xc3\xa4germeister",\n                    Price = 15.95M,\n                    \n                    Category = Categories["Alcoholic"],\n                    ImageUrl = "http://imgh.us/jagermeisterL.jpg",\n                    InStock = false,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/jagermeisterS.jpg"\n                },\n                new Drink\n                {\n                    Name = "Champagne",\n                    Price = 15.95M,\n                    \n                    Category = Categories["Alcoholic"],\n                    ImageUrl = "http://imgh.us/champagneL.jpg",\n                    InStock = false,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/champagneS.jpg"\n                },\n                new Drink\n                {\n                    Name = "Pi\xc3\xb1a colada ",\n                    Price = 15.95M,\n                    \n                    Category = Categories["Alcoholic"],\n                    ImageUrl = "http://imgh.us/pinaColadaL.jpg",\n                    InStock = false,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/pinaColadaS.jpg"\n                },\n                new Drink\n                {\n                    Name = "White Russian",\n                    Price = 15.95M,\n                    \n                    Category = Categories["Alcoholic"],\n                    ImageUrl = "http://imgh.us/whiteRussianL.jpg",\n                    InStock = false,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/whiteRussianS.jpg"\n                },\n                new Drink\n                {\n                    Name = "Long Island Iced Tea",\n                    Price = 15.95M,\n                    \n                    Category = Categories["Alcoholic"],\n                    ImageUrl = "http://imgh.us/longTeaL.jpg",\n                    InStock = false,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/islandTeaS.jpg"\n                },\n                new Drink\n                {\n                    Name = "Vodka",\n                    Price = 15.95M,\n                    \n                    Category = Categories["Alcoholic"],\n                    ImageUrl = "http://imgh.us/vodkaL.jpg",\n                    InStock = false,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/vodkaS.jpg"\n                },\n                new Drink\n                {\n                    Name = "Gin and tonic",\n                    Price = 15.95M,\n                    \n                    Category = Categories["Alcoholic"],\n                    ImageUrl = "http://imgh.us/ginTonicL.jpg",\n                    InStock = false,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/ginTonicS.jpg"\n                },\n                new Drink\n                {\n                    Name = "Cosmopolitan",\n                    Price = 15.95M,\n                    \n                    Category = Categories["Alcoholic"],\n                    ImageUrl = "http://imgh.us/cosmopolitanL.jpg",\n                    InStock = false,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/cosmopolitanS.jpg"\n                },\n                new Drink\n                {\n                    Name = "Tea ",\n                    Price = 12.95M,\n                    \n                    Category = Categories["Non-alcoholic"],\n                    ImageUrl = "http://imgh.us/teaL.jpg",\n                    InStock = true,\n                    IsPreferredDrink = true,\n                    ImageThumbnailUrl = "http://imgh.us/teaS.jpg"\n                },\n                new Drink\n                {\n                    Name = "Water ",\n                    Price = 12.95M,\n                    \n                    Category = Categories["Non-alcoholic"],\n                    ImageUrl = "http://imgh.us/waterL.jpg",\n                    InStock = true,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/waterS_1.jpg"\n                },\n                new Drink\n                {\n                    Name = "Coffee ",\n                    Price = 12.95M,\n                    \n                    Category = Categories["Non-alcoholic"],\n                    ImageUrl = "http://imgh.us/coffeeL.jpg",\n                    InStock = true,\n                    IsPreferredDrink = true,\n                    ImageThumbnailUrl = "http://imgh.us/coffeS.jpg"\n                },\n                new Drink\n                {\n                    Name = "Kvass",\n                    Price = 12.95M,\n                    \n                    Category = Categories["Non-alcoholic"],\n                    ImageUrl = "http://imgh.us/kvassL.jpg",\n                    InStock = true,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/kvassS.jpg"\n                },\n                new Drink\n                {\n                    Name = "Juice ",\n                    Price = 12.95M,\n                    \n                    Category = Categories["Non-alcoholic"],\n                    ImageUrl = "http://imgh.us/juiceL.jpg",\n                    InStock = true,\n                    IsPreferredDrink = false,\n                    ImageThumbnailUrl = "http://imgh.us/juiceS.jpg"\n                }\n            );\n        }\n\n        context.SaveChanges();\n    }\n\n    private static Dictionary<string, Category> categories;\n    public static Dictionary<string, Category> Categories\n    {\n        get\n        {\n            if (categories == null)\n            {\n                var genresList = new Category[]\n                {\n                    new Category { CategoryName = "Alcoholic", Description="All alcoholic drinks" },\n                    new Category { CategoryName = "Non-alcoholic", Description="All non-alcoholic drinks" }\n                };\n\n                categories = new Dictionary<string, Category>();\n\n                foreach (Category genre in genresList)\n                {\n                    categories.Add(genre.CategoryName, genre);\n                }\n            }\n\n            return categories;\n        }\n    }\n}\n}\n
Run Code Online (Sandbox Code Playgroud)\n

然后我的 Program.cs 文件:

\n
using DrinkAndGo.Data;\nusing DrinkAndGo.Data.Interfaces;\nusing DrinkAndGo.Data.Mocks;\nusing DrinkAndGo.Data.Repositories;\nusing Microsoft.EntityFrameworkCore;\nusing static System.Net.Mime.MediaTypeNames;\n\nvar builder = WebApplication.CreateBuilder(args);\n\nbuilder.Host.ConfigureServices(services =>\n{\n    services.AddTransient<IDrinkRepository, DrinkRepository>(); \n    services.AddTransient<ICategoryRepository, CategoryRepository>();\n    services.AddScoped<AppDbContext>();\n\n});\n\nbuilder.Services.AddControllersWithViews();\nbuilder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(\n    builder.Configuration.GetConnectionString("DefaultConnection")\n    ));\n\nvar app = builder.Build();\n\n\nif (app.Environment.IsDevelopment())\n{\n    app.UseDeveloperExceptionPage();\n}\nelse\n{\n    app.UseExceptionHandler("/Home/Error");\n    app.UseHsts();\n}\n\napp.UseHttpsRedirection();\napp.UseStaticFiles();\napp.UseRouting();\napp.UseAuthorization();\n\nDbInitializer.Seed(app);\napp.MapControllerRoute(\n    name: "default",\n    pattern: "{controller=Home}/{action=Index}/{id?}"\n    );\n\n\napp.Run();\n
Run Code Online (Sandbox Code Playgroud)\n

当我使用 IIS Express 运行应用程序时,Visual Studio 抛出以下异常:

\n
\n

System.InvalidOperationException\xc2\xa0:“无法从根提供程序解析范围服务“DrinkAndGo.Data.AppDbContext”。”

\n
\n

有人可以向我解释一下这个问题以及如何解决它吗?

\n

Gur*_*ron 40

您需要创建一个范围来解析范围服务。使用ServiceProviderServiceExtensions.CreateScope

public static void Seed(WebApplication app)
{
     using var scope = app.Services.CreateScope();
     AppDbContext context = scope.ServiceProvider.GetRequiredService<AppDbContext>();

    // use context
}
Run Code Online (Sandbox Code Playgroud)