服务单例范围 class(以及 dbcontext 的默认范围)的线程安全问题是什么?

What is the thread safety concern with singleton scope of the service class (and default scoped scope of dbcontext)?

控制器方法调用此 ValidateUser 方法。例如验证用户。该服务然后调用 dbcontext。例如进行数据库查询。

什么范围(transient/scoped/singleton)适合服务class?

据我了解,假设如果范围设置为单例,那么在应用程序的整个生命周期中只有 1 个 class 实例。即使默认情况下 DbContext 是有范围的,在整个生命周期中也只会存在 1 个连接(来自此服务 class 的实例)。

假设我设置为 transient,那么每个对服务 class 的请求都会创建一个新的 class 实例。由于 dbcontext 是有范围的,它将是 1 个用户请求生命周期的 1 个实例。

假设我设置为 scoped,那么每个用户对服务 class 的请求都会创建 class 的新实例。由于 dbcontext 是有范围的,它将是 1 个用户请求生命周期的 1 个实例

线程安全问题有哪些?

namespace MyApp.Services
{
    public class ValidateService : IValidateService
    {
    private readonly MyAppContext _context;

        public ValidateService(MyAppContext context)
        {
            _context = context;
        }

        public bool ValidateUser(UserDTO user)
        {
            return await _context.Users.AnyAsync(x => x.username == user.UserName);
        }
    }
}

在依赖注入期间,DbContext 被初始化为一个对象池,每个请求都会重复使用该对象池,因此具有范围生命周期的 DbContext 可以利用这一点。至于与dbcontext一起使用的Service class,建议匹配现有对象的最短生命周期(在这种情况下,因为dbcontext的作用域)。

以下链接中有更多信息。

https://codereview.stackexchange.com/questions/15703/threadsafe-dbcontext-in-singleton