© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
12 replies
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>()!)
);
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?

Edit:
AppDb
AppDb
is a class that inherrits from
DbContext
DbContext


Thanks in advance
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ ASP.NET Core Environment Variables in Dependency Injection
C#CC# / help
3y ago
Unit Testing Classes with Dependency Injection (ASP.NET Core)
C#CC# / help
3y ago
Issue with AddUserStore in asp.net core
C#CC# / help
3y ago
Routing issue with ASP.Net Core
C#CC# / help
4y ago