Scope


  Scope<T> 抽象类用于在一个线程范围内共享资源。使用静态属性 Current 返回当前线程内是否定义了其实例。如下所示:

public SerializeScope : Scope<SerializeScope>
{
    public SerializeScope(ISerializer serializer)
    {
        Serializer = serializer;
    }
    
    public ISerializer Serializer { get; private set; }
}

[TestMethod]
public void TestScope()
{
    var serializer = new JsonSerializer();
    using (var scope = new SerializeScope(serializer))
    {
        SerializeData();
    }
}

private void SerializeData()
{
    var serializer = SerializeScope.Current?.Serializer;
    serializer.Serialize(new Person());
}

  以上的 SerializeScope 类承载了一个 ISerializer 实例,在当前线程范围内的任意方法里,都可以使用其 Current 属性得到唯一的实例。

  Scope<T> 类在异步编程中一样适用。如下所示:

[TestMethod]
public async Task TestScopeAsync()
{
    var serializer = new JsonSerializer();
    using (var scope = new SerializeScope(serializer))
    {
        await SerializeDataAsync();
    }
}

private async Task SerializeDataAsync()
{
    var serializer = SerializeScope.Current?.Serializer;
    serializer.SerializeAsync(new Person());
    return Task.CompletedTask;
}

  你可以使用 SetData 方法往 Scope 实例中添加键值对数据,使用 GetData 方法取出使用。