在Asp.Net Core应用程序的Singleton中使用范围服务 [英] Using a Scoped service in a Singleton in an Asp.Net Core app

查看:400
本文介绍了在Asp.Net Core应用程序的Singleton中使用范围服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Asp.Net Core应用程序中,我需要一个单例服务,可以在应用程序的生命周期内对其进行重用。要构造它,我需要一个 DbContext (来自EF Core),但是它是作用域服务,并且不是线程安全的。

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 it is a scoped service and not thread safe.

因此,我正在使用以下模式构建单例服务。看起来有点怪异,因此我想知道这是否可以接受并且不会导致任何问题吗?

Therefore I am using the following pattern to construct my singleton service. It looks kinda hacky, therefore I was wondering whether this is an acceptable approach and won't lead to any problems?

services.AddScoped<IPersistedConfigurationDbContext, PersistedConfigurationDbContext>();
services.AddSingleton<IPersistedConfigurationService>(s =>
{
    ConfigModel currentConfig;
    using (var scope = s.CreateScope())
    {
        var dbContext = scope.ServiceProvider.GetRequiredService<IPersistedConfigurationDbContext>();
        currentConfig = dbContext.retrieveConfig();            
    }
    return new PersistedConfigurationService(currentConfig);
});

...

public class ConfigModel
{
    string configParam { get; set; }
}


推荐答案

尽管依赖注入:服务生存期 ASP.NET Core中的文档说:

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!

但是另一个可能的解决方案是使用 IHostedService 。这是有关它的详细信息:

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

在后台任务(IHostedService)中使用作用域服务

这篇关于在Asp.Net Core应用程序的Singleton中使用范围服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆