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

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

问题描述

在我的 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.

因此,我使用以下模式来构建我的单例服务.它看起来有点 hacky,因此我想知道这是否是一种可以接受的方法并且不会导致任何问题?

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 应用程序的单例中使用 Scoped 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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