如何在 C# 异步构造函数中设置只读 属性

How to set a readonly property in a C# async constructor

我在 ASP .Net Core 2.2 Web API 中有一项服务。构造函数是异步的,因为它调用异步方法。但是因为构造函数是异步的,所以它抱怨试图初始化一个 属性.

public class MyService
{
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public async Task MyService(IServiceScopeFactory serviceScopeFactory)
    {
        this._serviceScopeFactory = serviceScopeFactory;
        await DoSomething();
    }
}

它给我这个错误:

"A readonly field cannot be assigned to (except in a constructor or a variable initializer)"

有什么想法吗?

正如上面评论中提到的用户,我误以为我可以使构造函数异步。

Mathew Watson 和 Stephen Cleary 为我提供了 link 一个很好的替代方案来解决我的问题:https://blog.stephencleary.com/2013/01/async-oop-2-constructors.html

总结:

工厂模式 使用静态创建方法,使类型成为自己的工厂:

public sealed class MyClass
{
  private MyData asyncData;
  private MyClass() { ... }

  private async Task<MyClass> InitializeAsync()
  {
    asyncData = await GetDataAsync();
    return this;
  }

  public static Task<MyClass> CreateAsync()
  {
    var ret = new MyClass();
    return ret.InitializeAsync();
  }
}

public static async Task UseMyClassAsync()
{
  MyClass instance = await MyClass.CreateAsync();
  ...
}

解决问题的一个常见示例是在 class 上创建一个静态方法,然后从那里调用 async 方法以及构造函数。

public class MyService
{
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public static async Task<MyService> BuildMyService(IServiceScopeFactory serviceScopeFactory)
    {
        await DoSomething();
        return new MyService(serviceScopeFactory);
    }

    public MyService(IServiceScopeFactory serviceScopeFactory)
    {
        this._serviceScopeFactory = serviceScopeFactory;
    }
}