简体   繁体   English

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

[英]How to set a readonly property in a C# async constructor

I have a service in an ASP.Net Core 2.2 Web API.我在 ASP.Net Core 2.2 Web API 中有一项服务。 The constructor is async because it calls an async method.构造函数是异步的,因为它调用异步方法。 But because the constructor is async, it's complaining about trying to initialize a property.但是因为构造函数是异步的,所以它会抱怨试图初始化一个属性。

public class MyService
{
    private readonly IServiceScopeFactory _serviceScopeFactory;

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

It gives me this error:它给了我这个错误:

"A readonly field cannot be assigned to (except in a constructor or a variable initializer)" “不能将只读字段分配给(构造函数或变量初始化程序除外)”

Any ideas?有任何想法吗?

As users mentioned in the comments above, I was mistaken to think that I could make a constructor async.正如用户在上面的评论中提到的,我错误地认为我可以使构造函数异步。

Mathew Watson and Stephen Cleary provided me with a link with a good alternative to my problem: https://blog.stephencleary.com/2013/01/async-oop-2-constructors.html Mathew Watson 和 Stephen Cleary 为我提供了一个很好的解决问题的链接: https://blog.stephencleary.com/2013/01/async-oop-2-constructors.html

Summary:概括:

Factory Pattern Use a static creation method, making the type its own factory:工厂模式使用 static 创建方法,使类型成为自己的工厂:

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();
  ...
}

One common example to solve your problem is to create a static method on the class and call the async method from there and well as the constructor.解决您的问题的一个常见示例是在 class 上创建一个 static 方法,并从那里调用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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM