简体   繁体   中英

ASP.NET Core 2.1 does not recognize Configuration extension

I'm trying to setting up my project but I'm always keep getting this error :

Cannot convert lambda to type 'ServiceLifetime' because it is not a delegate type.

In my Startup class I did :

public Startup(IConfiguration configuration)
{
     Configuration = configuration;
}

public IConfiguration Configuration { get; }

And

public void ConfigureServices(IServiceCollection services)
{
     services.AddDbContext<ServiceProvider>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionStrings")));
}

I even tried to install the package Microsoft.Extensions.Configuration; but still I'm getting the same error!

Problem is you are using ServiceProvider as your DbContextType in services.AddDbContext<TContext> . Replace the services.AddDbContext<ServiceProvider> with services.AddDbContext<YourDbContext> as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<YourDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionStrings")));
}

You are passing ServiceProvider instead of a class of type DbContext. Add a new class derived from DbContext. So here you need to create a class like this:

public class ApplicationDbContext: DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options){
}
}

and in startup class:

public void ConfigureServices(IServiceCollection services)
{
 services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionStrings")));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM