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

元气小坏坏 提交于 2019-12-06 10:39:11

You are trying to inject the context into the Configure method which wont work. Remove the injected context from the Configure method and instead inject the service provider and try to resolve the context within the method.

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's answer got me on the right track but you don't actually need that many steps, at least in version 2.0 and up:

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

You don't need to return anything from ConfigureServices or build an intermediate provider in the version I'm running (2.0)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!