I'm a little bit noob with this and I would like to ask the following:
I'm trying to Inject a MyDbContext class vía DI and tried 2 things:
First, in Program.cs
I've got
builder.Services.AddScoped<MyDbContext>(p => new MyDbContext(builder.Configuration.GetConnectionString("ApiDotnetDb")));
In the MyDbContext
class I've got:
private readonly String _connString;
public MyDbContext(String connString)
{
this._connString = connString;
}
protected override void OnConfiguring(DbContextOptionsBuilder opt)
{
opt.UseMySQL(this._connString);
}
And everything compile and its ok but if I try:
In Program.cs
builder.Services.AddDbContext<MyDbContext>(opt => opt.UseMySQL(builder.Configuration.GetConnectionString("ApiDotnetDb")), ServiceLifetime.Scoped,
ServiceLifetime.Scoped);
And then in MyDbContextClass
like this:
public MyDbContext(DbContextOptions<DbContext> options) : base(options)
{
}
I get
System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: webapi.MyDbContext Lifetime: Scoped ImplementationType: webapi.MyDbContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Microsoft.EntityFrameworkCore.DbContext]' while attempting to activate 'webapi.MyDbContext'.)'
What could it be? Thanks
CodePudding user response:
Change the generic argument for DbContextOptions<T>
to use your derived DbContext
class:
public MyDbContext( DbContextOptions<MyDbContext> options )
: base( options )
{
}