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
And it wasn't able to resolve
I also tried with DbContext
And the 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 advance8 Replies
putting
!
behind variables, does not change the behavior
it just tells the compiler "i know it looks like this could be null, i (the developer) made sure it is not null", so the compiler does not keep telling you this variable could be null and that you should check it
if you wanna throw if the type can not be resolved you can use provider.GetRequiredService<T>()
instead 😉
the "Cannot resolve scoped service 'RemoteGatewayManager.Types.Classes.AppDb' from root provider" error just says you did not create a scope before trying to resolve
in asp.net core there should be a scope created for each client-request, so you dont have to worry about it there
but in backgroundservices and similar you will have to create a scope before resolving scoped-services 😉putting ! behind variables, does not change the behaviorAh yeah sorry i think i mistaken that for another language how do i know that the
AppDb
is registered as scoped service? 🤔probably says so somewhere in the documentation ^^
but if you think about it, it makes sense, since you dont want database accesses from different requests to influence each other
registering the db-context as scoped service, makes sure you get separate db-contexts for separate requests
does that mean have to use this https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.serviceproviderserviceextensions.createscope?view=dotnet-plat-ext-6.0 to create a scope first. and then get the dbcontext?
ServiceProviderServiceExtensions.CreateScope(IServiceProvider) Meth...
Creates a new IServiceScope that can be used to resolve scoped services.
if you want to resolve it in a background service or similar, yeah
in controllers and stuff called from controllers you dont need to worry about it, since asp.net core will create scopes for each request for you already
yeah i'm using it in hosted services and background services
here is a article about how to use scopes in background services 😉
https://learn.microsoft.com/en-us/dotnet/core/extensions/scoped-service
Use scoped services within a BackgroundService - .NET
Learn how to use scoped services within a BackgroundService in .NET.
I see i could get
IServiceProvider
in the service
thanks a lot that answers it 😄
that resolves my misunderstanding too 😄