簡體   English   中英

InvalidOperationException:無法解析范圍服務

[英]InvalidOperationException: Cannot resolve scoped service

InvalidOperationException:無法從根提供程序解析作用域服務'DrinkAndGo.Data.AppDbContext'。 DbInitializer.cs中的DrinkAndGo.Data.DbInitializer.Seed(IApplicationBuilder applicationBuilder)+13 AppDbContext上下文= Startup.cs中的DrinkAndGo.Startup.Configure(IApplicationBuilder app,IHostingEnvironment env)+46 DbInitializer.Seed(app);

  using DrinkAndGo.Data.Models;
  using Microsoft.AspNetCore.Builder;
  using Microsoft.Extensions.DependencyInjection;
  using System.Collections.Generic;
  using System.Linq;

namespace DrinkAndGo.Data
{
public class 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.Drinks.Any())
        {
            context.AddRange
            (
                new Drink
                {
                    Name = "Beer",
                    Price = 7.95M,
                    ShortDescription = "The most widely consumed alcohol",
                    LongDescription = "Beer is the world's ",
                    Category = Categories["Alcoholic"],
                    ImageUrl = "http://imgh.us/beerL_2.jpg",
                    InStock = true,
                    IsPreferredDrink = true,
                    ImageThumbnailUrl = "http://imgh.us/beerS_1.jpeg"
                },
                new Drink
                {
                    Name = "Rum & Coke",
                    Price = 12.95M,
                    ShortDescription = "Cocktail made of cola, lime and rum.",
                    LongDescription = "The world's second most popular drink",
                    Category = Categories["Alcoholic"],
                    ImageUrl = "http://imgh.us/rumCokeL.jpg",
                    InStock = true,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/rumAndCokeS.jpg"
                },
                new Drink
                {
                    Name = "Tequila ",
                    Price = 12.95M,
                    ShortDescription = "Beverage made from the blue agave plant.",
                    LongDescription = "Tequila (Spanish About this sound [teˈkila].",
                    Category = Categories["Alcoholic"],
                    ImageUrl = "http://imgh.us/tequilaL.jpg",
                    InStock = true,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/tequilaS.jpg"
                },
                new Drink
                {
                    Name = "Wine ",
                    Price = 16.75M,
                    ShortDescription = "A very elegant alcoholic drink",
                    LongDescription = "Contrary to popular belief=.",
                    Category = Categories["Alcoholic"],
                    ImageUrl = "http://imgh.us/wineL.jpg",
                    InStock = true,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/wineS.jpg"
                },
                new Drink
                {
                    Name = "Margarita",
                    Price = 17.95M,
                    ShortDescription = "A cocktail with sec, tequila and lime",
                    Category = Categories["Alcoholic"],
                    LongDescription = "Contrary to popular belief=",
                    ImageUrl = "http://imgh.us/margaritaL.jpg",
                    InStock = true,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/margaritaS.jpg"
                },
                new Drink
                {
                    Name = "Whiskey with Ice",
                    Price = 15.95M,
                    ShortDescription = "The best way to taste whiskey",
                    LongDescription = "Contrary to popular belief,,
                    Category = Categories["Alcoholic"],
                    ImageUrl = "http://imgh.us/whiskyIceL.jpg",
                    InStock = false,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/whiskeyS.jpg"
                },
                new Drink
                {
                    Name = "Jägermeister",
                    Price = 15.95M,
                    ShortDescription = "A German digestif made with 56 herbs",
                    LongDescription = "",
                    Category = Categories["Alcoholic"],
                    ImageUrl = "http://imgh.us/jagermeisterL.jpg",
                    InStock = false,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/jagermeisterS.jpg"
                },
                new Drink
                {
                    Name = "Champagne",
                    Price = 15.95M,
                    ShortDescription = "That is how sparkling wine can be called",
                    LongDescription = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.",
                    Category = Categories["Alcoholic"],
                    ImageUrl = "http://imgh.us/champagneL.jpg",
                    InStock = false,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/champagneS.jpg"
                },
                new Drink
                {
                    Name = "Piña colada ",
                    Price = 15.95M,
                    ShortDescription = "A sweet cocktail made with rum.",
                    LongDescription = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.",
                    Category = Categories["Alcoholic"],
                    ImageUrl = "http://imgh.us/pinaColadaL.jpg",
                    InStock = false,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/pinaColadaS.jpg"
                },
                new Drink
                {
                    Name = "White Russian",
                    Price = 15.95M,
                    ShortDescription = "A cocktail made with vodka ",
                    LongDescription = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.",
                    Category = Categories["Alcoholic"],
                    ImageUrl = "http://imgh.us/whiteRussianL.jpg",
                    InStock = false,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/whiteRussianS.jpg"
                },
                new Drink
                {
                    Name = "Long Island Iced Tea",
                    Price = 15.95M,
                    ShortDescription = "Aa mixed drink made with tequila.",
                    LongDescription = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.",
                    Category = Categories["Alcoholic"],
                    ImageUrl = "http://imgh.us/longTeaL.jpg",
                    InStock = false,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/islandTeaS.jpg"
                },
                new Drink
                {
                    Name = "Vodka",
                    Price = 15.95M,
                    ShortDescription = "A distilled beverage with water and ethanol.",
                    LongDescription = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.",
                    Category = Categories["Alcoholic"],
                    ImageUrl = "http://imgh.us/vodkaL.jpg",
                    InStock = false,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/vodkaS.jpg"
                },
                new Drink
                {
                    Name = "Gin and tonic",
                    Price = 15.95M,
                    ShortDescription = "Made with gin and tonic water poured over ice.",
                    LongDescription = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.",
                    Category = Categories["Alcoholic"],
                    ImageUrl = "http://imgh.us/ginTonicL.jpg",
                    InStock = false,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/ginTonicS.jpg"
                },
                new Drink
                {
                    Name = "Cosmopolitan",
                    Price = 15.95M,
                    ShortDescription = "Made with vodka, triple sec, cranberry juice.",
                    LongDescription = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.",
                    Category = Categories["Alcoholic"],
                    ImageUrl = "http://imgh.us/cosmopolitanL.jpg",
                    InStock = false,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/cosmopolitanS.jpg"
                },
                new Drink
                {
                    Name = "Tea ",
                    Price = 12.95M,
                    ShortDescription = "Made by leaves of the tea plant in hot water.",
                    LongDescription = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.",
                    Category = Categories["Non-alcoholic"],
                    ImageUrl = "http://imgh.us/teaL.jpg",
                    InStock = true,
                    IsPreferredDrink = true,
                    ImageThumbnailUrl = "http://imgh.us/teaS.jpg"
                },
                new Drink
                {
                    Name = "Water ",
                    Price = 12.95M,
                    ShortDescription = " It makes up more than half of your body weight ",
                    LongDescription = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.",
                    Category = Categories["Non-alcoholic"],
                    ImageUrl = "http://imgh.us/waterL.jpg",
                    InStock = true,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/waterS_1.jpg"
                },
                new Drink
                {
                    Name = "Coffee ",
                    Price = 12.95M,
                    ShortDescription = " A beverage prepared from coffee beans",
                    LongDescription = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.",
                    Category = Categories["Non-alcoholic"],
                    ImageUrl = "http://imgh.us/coffeeL.jpg",
                    InStock = true,
                    IsPreferredDrink = true,
                    ImageThumbnailUrl = "http://imgh.us/coffeS.jpg"
                },
                new Drink
                {
                    Name = "Kvass",
                    Price = 12.95M,
                    ShortDescription = "A very refreshing Russian beverage",
                    LongDescription = "Contrary to popular belief, Lorem Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.",
                    Category = Categories["Non-alcoholic"],
                    ImageUrl = "http://imgh.us/kvassL.jpg",
                    InStock = true,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/kvassS.jpg"
                },
                new Drink
                {
                    Name = "Juice ",
                    Price = 12.95M,
                    ShortDescription = "Naturally contained in fruit or vegetable tissue.",
                    LongDescription = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable accompanied by English versions from the 1914 translation by H. Rackham.",
                    Category = Categories["Non-alcoholic"],
                    ImageUrl = "http://imgh.us/juiceL.jpg",
                    InStock = true,
                    IsPreferredDrink = false,
                    ImageThumbnailUrl = "http://imgh.us/juiceS.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 = "Alcoholic", Description="All alcoholic drinks" },
                    new Category { CategoryName = "Non-alcoholic", Description="All non-alcoholic drinks" }
                };

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

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

            return categories;
        }
    }
}}

這是我的啟動頁面:

namespace DrinkAndGo
{
    public class Startup
    {
        // 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

        private IConfigurationRoot _configurationRoot;

        public Startup(IHostingEnvironment hostingEnvironment)
        {
            _configurationRoot = new ConfigurationBuilder().SetBasePath(hostingEnvironment.ContentRootPath).AddJsonFile("appsettings.json").Build();
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppDbContext>(options => options.UseSqlServer(_configurationRoot.GetConnectionString("DefaultConnection")));
            services.AddTransient<IDrinkRepository, DrinkRepository>(); // Adding a service
            services.AddTransient<ICategoryRepository, CategoryRepository>(); // Adding a service
            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();
            app.UseStatusCodePages();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();

            DbInitializer.Seed(app);
        }
    }
}

您可以從IServiceProviders GetRequiredService<T>方法解析AppDbContext。

將IServiceProvider作為參數添加到Startup類中的Configure方法中,運行時將為您注入

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
    app.UseDeveloperExceptionPage();
    app.UseStatusCodePages();
    app.UseStaticFiles();
    app.UseMvcWithDefaultRoute();

    DbInitializer.Seed(serviceProvider.GetRequiredService<AppDbContext>());
}

然后將AppDbContext作為參數添加到Seed方法中

public static void Seed(AppDbContext context)

在“啟動”頁面上:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env ,IServiceProvider serviceProvider)
        {
            app.UseDeveloperExceptionPage();
            app.UseStatusCodePages();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();

            DbInitializer.Seed(serviceProvider);
        }

並在:DbInitializer

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM