InvalidOperationException:无法解析作用域服务

时间:2018-04-17 16:16:29

标签: c# asp.net dependency-injection

  

InvalidOperationException:无法解析作用域服务' DrinkAndGo.Data.AppDbContext'来自root提供者。   DbInitializer.cs中的DrinkAndGo.Data.DbInitializer.Seed(IApplicationBuilder applicationBuilder)   +13               AppDbContext context =   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;
        }
    }
}}

这是我的StartUp页面:

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);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您可以从IServiceProviders echo "GATTT ATCGT" | sed -r 's/([^T]*T+)/\1\n/g;' | sed '/^$/d' GATTT AT CGT 方法解析AppDbContext。

将IServiceProvider作为参数添加到Startup类中的Configure方法,运行时将为您注入

GetRequiredService<T>

然后将AppDbContext添加为Seed方法

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

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

答案 1 :(得分:1)

在StartUp页面:

ie.document.querySelector("input[onclick=go('CSV')]").Click

并在:DbInitializer

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

            DbInitializer.Seed(serviceProvider);
        }
相关问题