Cannot resolve scoped service from root provider ASP.NET Core
Cannot resolve scoped service from root provider ASP.NET Core
Today in this article, we will cover below aspects,
Issue Description
.NET Core runtime gives error,
Resolution
The error seems could occur at multiple places depending on your specific implementation while using the services in your code base.
As we know one can register the Services as Singleton or Scoped or Transient.
While scope service instances are created once per request it is often recommended they are resolved using a scoped instance of Application Builder. Then followed by using a service provider one can resolve the dependencies.
You might need to consider the below aspects also before resolving the issue,
- How a lifetime of service instances is registered.
- How the instance is initialized.
- How the instance is resolved.
I was able to resolve the issue using the scoped service provider instance using the below code base. One can take a similar approach to resolve their specific issues.
or you can use using the scope for the required DI as below,
If you need to resolve services within ConfigureServices() method then one can use the below approach too to resolve the instances,
1
2
3
4
|
services.AddSingleton(provider => new MapperConfiguration(cfg => { cfg.AddProfile( new SourceMappingProfile(provider.CreateScope().ServiceProvider.GetService<IEmployeeType>())); }).CreateMapper()); |
That’s All!
Did I miss anything else in these resolution steps?
Did the above steps resolve your issue? Please sound off your comments below!
Happy Coding !!
参考地址:https://www.thecodebuzz.com/cannot-resolve-scoped-service-from-root-provider-asp-net-core/