gpt4 book ai didi

asp.net-core - IOptionsMonitor 与 IOptionsSnapshot 之间的区别

转载 作者:行者123 更新时间:2023-12-01 17:31:23 26 4
gpt4 key购买 nike

根据this answerIOptionsMonitor 在 DI 容器中注册为单例,并且能够通过 OnChange 事件订阅检测更改。它有一个 CurrentValue 属性。

另一方面,IOptionsSnapshot 注册为作用域,并且还具有通过读取每个请求的最后选项来进行更改检测的功能,但它没有OnChange 事件。它有一个 Value 属性。

例如,使用两者注入(inject) View 可以给我们带来完全相同的行为:

using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Options;
using UsingOptionsSample.Models;
using UsingOptionsSample.Services;

namespace UsingOptionsSample.Pages
{
public class MyOptions
{
public MyOptions()
{
// Set default value.
Option1 = "value1_from_ctor";
}

public string Option1 { get; set; }
public int Option2 { get; set; } = 5;
}

public class OptionsTestModel : PageModel
{
private readonly MyOptions _snapshotOptions;
private readonly MyOptions _monitorOptions;

public OptionsTestModel(
IOptionsMonitor<MyOptions> monitorOptionsAcessor,
IOptionsSnapshot<MyOptions> snapshotOptionsAccessor)
{
_snapshotOptions = snapshotOptionsAccessor.Value;
_monitorOptions = monitorOptionsAcessor.CurrentValue;
}

public string SnapshotOptions { get; private set; }
public string MonitorOptions { get; private set; }

public void OnGetAsync()
{
//Snapshot options
var snapshotOption1 = _snapshotOptions.Option1;
var snapshotOption2 = _snapshotOptions.Option2;
SnapshotOptions =
$"snapshot option1 = {snapshotOption1}, " +
$"snapshot option2 = {snapshotOption2}";

//Monitor options
var monitorOption1 = _monitorOptions.Option1;
var monitorOption2 = _monitorOptions.Option2;
MonitorOptions =
$"monitor option1 = {monitorOption1}, " +
$"monitor option2 = {monitorOption2}";
}
}
}

那么,如果这两个接口(interface)/实现看起来像相同的东西,只是具有不同的生命周期,那么它们有什么意义呢?代码是based on this sample ,令人惊讶的是,其中不包含 IOptionsMonitor 使用示例。

如果两者都返回选项的“当前值”,为什么一个具有“Value”属性而另一个具有“CurrentValue”?

为什么/何时应该使用 IOptionsSnapshot 而不是 IOptionsMonitor

我认为我没有弄清楚,我一定错过了有关这些和依赖注入(inject)的一些非常重要的方面。

最佳答案

IOptionsMonitor是一个单例服务,可以随时检索当前选项值,这在单例依赖项中特别有用。

IOptionsSnapshot是一项范围服务,并提供 IOptionsSnapshot<T> 时选项的快照对象被构造。选项快照设计用于 transient 范围依赖项。

Use IOptions<T> when you are not expecting your config values to change. Use IOptionsSnaphot<T> when you are expecting your values to change but want it to be consistent for the entirety of a request. Use IOptionsMonitor<T> when you need real time values.

关于asp.net-core - IOptionsMonitor 与 IOptionsSnapshot 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50788988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com