在单例服务的构造函数中访问 dbcontext

Accessing dbcontext in Constructor of Singleton Service

提问人:Prv 提问时间:10/22/2023 更新时间:10/22/2023 访问量:45

问:

场景: 在 blazor Web 程序集应用程序的服务器项目中:我有一个服务,它将利用数据库中的某些元数据。此元数据只会随着架构的更改而更改,而不是在正常应用程序执行期间更改。

我的目的是创建一个可以从控制器调用的单例服务来访问此信息。我打算捕获此元数据一次,然后通过服务提供。

我相信这样做的方法是使 dbcontext 在服务的构造函数中可用,捕获信息,然后销毁 dbccontext,因为在服务中不再需要它。其他方法会将此元数据传递给调用方。

问题 1:这种方法有意义吗?

基本逻辑为:

public ServiceConstructor()
{
Get copy of the dbcontext
Do some work using the dbcontext
destroy the dbcontext.
}

Queston 2:如何从作用域服务中获取 dbcontext 的副本,在不将其作为参数传递给构造函数的情况下执行此操作是否有意义?

依赖项注入 blazor 单例 blazor-webassembly

评论


答:

1赞 MrC aka Shaun Curtis 10/22/2023 #1

我的方法是将数据缓存在单例服务中,但通过作用域服务访问它。

访问数据的第一个作用域服务发现它为空,因此使用 DBContext 从 .此后,任何进一步的作用域服务都将访问单例中缓存的数据。DbContextFactory

我不会将 a 传递到单例中以供它使用。DbContext

像这样:

public class DataSingletonService
{
    internal string? Value { get; private set; }

    internal void SetData(string value)
        => Value = value;
}

public class DataScopedService
{
    private DataSingletonService _dataSingletonService;
    // define the DBContextFactory here

    public DataScopedService(DataSingletonService dataSingletonService)
    {
        // Get the DBContextFactory here
        _dataSingletonService = dataSingletonService;
    }

    public async ValueTask<string> GetDataAsync()
    {
        if (_dataSingletonService.Value is null)
        {
            // using dbContext =  DbContextFactory.GetContext();
            // fake a db async call to the DbContext
            await Task.Delay(500);
            _dataSingletonService.SetData("Now Set");
        }

        return _dataSingletonService.Value ?? string.Empty;
    }
}

评论

0赞 Prv 10/23/2023
谢谢MrC。这个线索对我有用。