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>()!));
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
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>()!));
builder.Services.AddDbContext<AppDb>();builder.Services.AddHostedService(provider => new DbMigrator(provider.GetService<ILogger<DbMigrator>>()!, provider.GetService<AppDb>()!));
And the
provider.GetService<AppDb>()!
provider.GetService<AppDb>()!
returns
null
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?