问题
I've just upgraded to ASP.NET Core 2 Preview 2 and ran into a problem with the depedency injection. I get
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.
I didn't have this problem when using the old version.
DbContext (GenericDbContext):
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");
}
}
}
}
Exception:
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)
回答1:
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);
}
回答2:
@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)
来源:https://stackoverflow.com/questions/45526530/getting-could-not-resolve-a-service-of-type-after-upgrading-to-core-2-previ