我在ASP .Net Core 2.2 Web API中提供服务。构造函数是异步的,因为它调用了async方法。但是因为构造函数是异步的,所以它抱怨尝试初始化属性。
public class MyService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
public async Task MyService(IServiceScopeFactory serviceScopeFactory)
{
this._serviceScopeFactory = serviceScopeFactory;
await DoSomething();
}
}
它给了我这个错误:
“无法分配只读字段(在构造函数或变量初始化程序中除外)”
有什么想法吗?
答案 0 :(得分:4)
正如用户在上面的评论中提到的那样,我误以为我可以使构造函数异步。
Mathew Watson和Stephen Cleary为我提供了一个链接,可以代替我的问题:https://blog.stephencleary.com/2013/01/async-oop-2-constructors.html
摘要:
工厂模式 使用静态创建方法,将类型设为自己的工厂:
w = (Window().partitionBy(col("number"),col("id")).orderBy(F.col("timestampGMT").cast('long')).rangeBetween(-days(27), 0))
df1 = df.withColumn('lw_4weeksCY_SALES_DOLLARS', F.sum("CY_SALES_DOLLARS").over(w)).withColumn('lw_4weeksCY_SALES_UNITS', F.sum("CY_SALES_UNITS")
答案 1 :(得分:2)
解决问题的一个常见示例是在类上创建一个静态方法,然后从那里以及构造函数中调用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;
}
}