Using a Scoped service in a Singleton in an Asp.Net Core app

后端 未结 3 1070
清歌不尽
清歌不尽 2021-01-21 00:01

In my Asp.Net Core App I need a singleton service that I can reuse for the lifetime of the application. To construct it, I need a DbContext (from the EF Core), but

3条回答
  •  执念已碎
    2021-01-21 00:38

    Although Dependency injection: Service lifetimes documentation in ASP.NET Core says:

    It's dangerous to resolve a scoped service from a singleton. It may cause the service to have incorrect state when processing subsequent requests.

    But in your case this is not the issue. Actually you are not resolving the scoped service from singleton. Its just getting an instance of scoped service from singleton whenever it requires. So your code should work properly without any disposed context error!

    But another potential solution can be using IHostedService. Here is the details about it:

    Consuming a scoped service in a background task (IHostedService)

提交回复
热议问题