C#C
C#4y ago
kunio_kun

Dependency Injection in ASP.NET Core and issue with null suppresion

Hi, I'm having some issues with null suppression and dependency injection in ASP.NET Core

I have this block of code
builder.Services.AddDbContext<AppDb>();
builder.Services.AddHostedService(provider =>
    new DbMigrator(provider.GetService<ILogger<DbMigrator>>()!, provider.GetService<AppDb>()!)
);


And it wasn't able to resolve
Cannot resolve scoped service 'RemoteGatewayManager.Types.Classes.AppDb' from root provider


I also tried with DbContext
builder.Services.AddDbContext<AppDb>();
builder.Services.AddHostedService(provider =>
    new DbMigrator(provider.GetService<ILogger<DbMigrator>>()!, provider.GetService<AppDb>()!)
);


And the
provider.GetService<AppDb>()!
returns
null
, but doesn't throw. Isn't it supposed to throw for being null?
Also why is it returning null instead of telling that it is not able to resolve service?

Edit: AppDb is a class that inherrits from DbContext

Thanks in advance
Was this page helpful?