升级到 Core 2 Preview 2 后获得 "Could not resolve a service of type .."

Getting "Could not resolve a service of type .." after upgrading to Core 2 Preview 2

我刚刚升级到 ASP.NET Core 2 Preview 2 并且 运行 遇到依赖注入问题。我得到

Could not resolve a service of type 'LC.Tools.API.Data.GenericDbContext' for the parameter 'context' of method 'Configure' on type 'LC.Tools.API.Startup' when running the project.

我用老版本没有这个问题

DbContext(通用数据库上下文):

namespace LC.Tools.API.Data
{
    public class GenericDbContext : DbContext
    {
        public GenericDbContext(DbContextOptions<GenericDbContext> options) : base(options) { }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            //Generic
            builder.Entity<Client>();
            builder.Entity<Graphic>();
            .
            .
            .
            .
            .

            //Shop
            builder.Entity<Models.Shop.Store>().ToTable("ShopClient");
            builder.Entity<Models.Shop.Category>().ToTable("ShopCategory");
            .
            .
            .
            .
            .
            .
    }
}

Startup.cs:

namespace LC.Tools.API
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();

            this.HostingEnvironment = env;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            services.AddDbContext<Data.GenericDbContext>(options => options.UseSqlServer(this.ConnectionString));

            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, Data.GenericDbContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseForwardedHeaders(new ForwardedHeadersOptions
                {
                    ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor,
                    ForwardLimit = 2
                });

                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }

            app.UseStaticFiles();
            app.UseMvc();

            Data.Debug.Init.Initalize(context, env);
        }

        private IHostingEnvironment HostingEnvironment { get; set; }

        public IConfigurationRoot Configuration { get; }

        private string ConnectionString
        {
            get
            {
                return this.HostingEnvironment.IsDevelopment() ? Configuration.GetConnectionString("Development") : Configuration.GetConnectionString("Production");
            }
        }
    }
}

异常:

An error occurred while starting the application.

InvalidOperationException: Cannot resolve scoped service 'LC.Tools.API.Data.GenericDbContext' from root provider.

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, ServiceProvider serviceProvider) Exception: Could not resolve a service of type 'LC.Tools.API.Data.GenericDbContext' for the parameter 'context' of method 'Configure' on type 'LC.Tools.API.Startup'.

Microsoft.AspNetCore.Hosting.Internal.ConfigureBuilder.Invoke(object instance, IApplicationBuilder builder)

InvalidOperationException: Cannot resolve scoped service
                    'LC.Tools.API.Data.GenericDbContext' from root provider.

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, ServiceProvider serviceProvider) Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType) Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) Microsoft.AspNetCore.Hosting.Internal.ConfigureBuilder.Invoke(object instance, IApplicationBuilder builder)

您正试图将上下文注入 Configure 方法,但该方法不起作用。从 Configure 方法中删除注入的上下文,而是注入服务提供者并尝试在方法中解析上下文。

public IServiceProvider ConfigureServices(IServiceCollection services) {
    services.AddOptions();
    services.AddDbContext<Data.GenericDbContext>(options => options.UseSqlServer(this.ConnectionString));

    services.AddMvc();

    // Build the intermediate service provider
    var serviceProvider = services.BuildServiceProvider();
    //return the provider
    return serviceProvider;
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                      ILoggerFactory loggerFactory, IServiceProvider serviceProvider) {
    //...Other code removed for brevity

    var context = serviceProvider.GetService<Data.GenericDbContext>();
    Data.Debug.Init.Initalize(context, env);
}

@Nkosi 的回答让我走上了正确的轨道,但实际上你不需要那么多步骤,至少在 2.0 及更高版本中是这样:

public void ConfigureServices(IServiceCollection services) {
    services.AddOptions();
    services.AddDbContext<Data.GenericDbContext>(options => options.UseSqlServer(this.ConnectionString));

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                      ILoggerFactory loggerFactory, IServiceProvider serviceProvider) {
    //...Other code removed for brevity

    var context = serviceProvider.GetService<Data.GenericDbContext>();
    Data.Debug.Init.Initalize(context, env);
}

您不需要 return 来自 ConfigureServices 的任何内容,也不需要在我 运行 (2.0)

的版本中构建中间提供程序